opencode-swarm 7.113.4 → 7.114.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.
Files changed (47) hide show
  1. package/.opencode/skills/brainstorm/SKILL.md +10 -8
  2. package/.opencode/skills/ci-fix-monitor/SKILL.md +2 -2
  3. package/.opencode/skills/clarify/SKILL.md +2 -2
  4. package/.opencode/skills/clarify-spec/SKILL.md +4 -4
  5. package/.opencode/skills/commit-pr/SKILL.md +32 -20
  6. package/.opencode/skills/council/SKILL.md +1 -1
  7. package/.opencode/skills/deep-dive/SKILL.md +3 -3
  8. package/.opencode/skills/design-docs/SKILL.md +2 -1
  9. package/.opencode/skills/discover/SKILL.md +2 -2
  10. package/.opencode/skills/engineering-conventions/SKILL.md +54 -1
  11. package/.opencode/skills/gate-attribution/SKILL.md +11 -8
  12. package/.opencode/skills/issue-ingest/SKILL.md +18 -14
  13. package/.opencode/skills/loop/SKILL.md +3 -4
  14. package/.opencode/skills/merge-queue-readiness/SKILL.md +6 -13
  15. package/.opencode/skills/phase-wrap/SKILL.md +30 -28
  16. package/.opencode/skills/plan/SKILL.md +8 -7
  17. package/.opencode/skills/resume/SKILL.md +5 -5
  18. package/.opencode/skills/running-tests/SKILL.md +3 -4
  19. package/.opencode/skills/specify/SKILL.md +2 -1
  20. package/.opencode/skills/swarm/SKILL.md +8 -0
  21. package/.opencode/skills/swarm-ci-monitor/SKILL.md +4 -4
  22. package/.opencode/skills/swarm-pr-feedback/SKILL.md +55 -38
  23. package/.opencode/skills/swarm-pr-subscribe/SKILL.md +2 -0
  24. package/.opencode/skills/test-file-split/SKILL.md +3 -5
  25. package/.opencode/skills/writing-tests/SKILL.md +98 -28
  26. package/README.md +2 -2
  27. package/dist/cli/{curator-llm-factory-b3g0g0cd.js → curator-llm-factory-26pyy8cq.js} +1 -1
  28. package/dist/cli/{curator-nh9raf1a.js → curator-wwyj379g.js} +1 -1
  29. package/dist/cli/{guardrail-explain-wpv5eskq.js → guardrail-explain-qzg7rr7f.js} +2 -2
  30. package/dist/cli/{hive-promoter-c0fd3j02.js → hive-promoter-kfjbydfj.js} +1 -1
  31. package/dist/cli/{index-10v7hrkj.js → index-2aszzcyk.js} +1 -1
  32. package/dist/cli/{index-ct9e0y0q.js → index-8phvk4v4.js} +58 -25
  33. package/dist/cli/{index-5yzr9fk6.js → index-gge9vh5s.js} +2 -2
  34. package/dist/cli/index.js +1 -1
  35. package/dist/commands/council.d.ts +0 -1
  36. package/dist/commands/registry.d.ts +3 -3
  37. package/dist/config/skill-mirrors.d.ts +13 -3
  38. package/dist/full-auto/state.d.ts +26 -0
  39. package/dist/index.js +20 -16
  40. package/dist/services/status-service.d.ts +16 -1
  41. package/dist/state.d.ts +9 -0
  42. package/dist/tools/create-tool.d.ts +9 -0
  43. package/dist/tools/test-runner.d.ts +0 -1
  44. package/package.json +2 -3
  45. package/dist/output/agent-writer.d.ts +0 -27
  46. package/dist/output/index.d.ts +0 -1
  47. package/dist/tools/knowledge-ack.d.ts +0 -15
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.113.4",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",".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/swarm",".opencode/skills/swarm-ci-monitor",".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","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",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"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},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","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","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.",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)}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,DEFAULT_MODELS,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.114.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",".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","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","drift:fix":"bun run scripts/drift-check.ts --fix --confirm",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"},dependencies:{"@opencode-ai/plugin":"^1.1.53","@opencode-ai/sdk":"^1.1.53","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight"],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]});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_oversight","coder","test_engineer"]},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_oversight"]},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"]},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer"]},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","coder","test_engineer"]},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","coder"]},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_oversight"]},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_oversight"]},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"]},quality_budget:{description:"code quality budget check",agents:["architect"]},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","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","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"]},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"]},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"]},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_oversight","test_engineer"]},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"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","test_engineer"]},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_oversight","test_engineer"]},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","explorer","architect"]},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"]},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","coder","test_engineer"]},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"]},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},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","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_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"]},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"]},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"]},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_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"]},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","critic_oversight","explorer","coder"]},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: 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.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is 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.",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","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic","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.",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)}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,DEFAULT_MODELS,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
 
@@ -647,7 +647,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
647
647
  `),validStartMs=[];for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(typeof parsed.startMs==="number"&&Number.isFinite(parsed.startMs))validStartMs.push(parsed.startMs)}catch{}}if(validStartMs.length===0)return null;return new Date(Math.min(...validStartMs)).toISOString()}catch{return null}}var SESSION_START_FILE="session-start.jsonl";var init_session_start_store=()=>{};import{existsSync as existsSync21,lstatSync as lstatSync5,mkdirSync as mkdirSync17,readFileSync as readFileSync15,rmSync as rmSync3}from"node:fs";import*as os12 from"node:os";import*as path47 from"node:path";function resolveDataDir(){let platform=process.platform,home=process.env.HOME||os12.homedir();if(platform==="win32")return path47.join(process.env.LOCALAPPDATA||path47.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")return path47.join(home,"Library","Application Support","opencode-swarm");return path47.join(process.env.XDG_DATA_HOME||path47.join(home,".local","share"),"opencode-swarm")}function resolveLinkBaseDir(){return path47.join(resolveDataDir(),"links")}function resolveLinkDir(linkId){return path47.join(resolveLinkBaseDir(),linkId)}function sanitizeLinkId(name){if(typeof name!=="string")return null;let cleaned=name.trim().toLowerCase().replace(/[^a-z0-9._-]+/g,"-").replace(/-+/g,"-").replace(/^[-.]+|[-.]+$/g,"").slice(0,MAX_LINK_ID_LENGTH).replace(/[-.]+$/g,"");if(cleaned.length===0)return null;let base=cleaned.split(".")[0];if(WINDOWS_RESERVED_NAMES.has(base))return null;return cleaned}function resolveLinkPointerPath(directory){return path47.join(directory,".swarm",LINK_POINTER_FILENAME)}function readLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);if(!existsSync21(pointerPath))return null;try{let raw=JSON.parse(readFileSync15(pointerPath,"utf-8"));if(!raw||typeof raw!=="object")return null;let obj=raw,linkId=obj.linkId;if(typeof linkId!=="string"||linkId.length===0)return null;let safeId=sanitizeLinkId(linkId);if(!safeId)return null;return{version:1,linkId:safeId,name:typeof obj.name==="string"?obj.name:void 0,createdAt:typeof obj.createdAt==="string"?obj.createdAt:new Date(0).toISOString(),source:obj.source==="auto"?"auto":"manual"}}catch{return null}}function getLinkedLocalKnowledgeStatus(directory){let localKnowledgePath=path47.join(directory,".swarm","knowledge.jsonl"),pointer=readLinkPointer(directory);if(!pointer)return{linked:!1,orphaned:!1,localKnowledgePath,resolvedKnowledgePath:localKnowledgePath,reason:"not_linked"};let resolvedKnowledgePath=path47.join(path47.resolve(resolveLinkDir(pointer.linkId)),"knowledge.jsonl");if(!existsSync21(localKnowledgePath))return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"};try{if(lstatSync5(localKnowledgePath).isSymbolicLink())return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_symlink"}}catch{return{linked:!0,orphaned:!1,localKnowledgePath,resolvedKnowledgePath,reason:"local_missing"}}return{linked:!0,orphaned:!0,localKnowledgePath,resolvedKnowledgePath,reason:"local_regular_file"}}async function writeLinkPointer(directory,pointer){let swarmDir=path47.join(directory,".swarm");mkdirSync17(swarmDir,{recursive:!0});let pointerPath=resolveLinkPointerPath(directory);await atomicWriteFile(pointerPath,JSON.stringify(pointer,null,2)),invalidateKnowledgeStoreDirCache(directory)}async function removeLinkPointer(directory){let pointerPath=resolveLinkPointerPath(directory);try{rmSync3(pointerPath,{force:!0})}finally{invalidateKnowledgeStoreDirCache(directory)}}function resolveKnowledgeStoreDir(directory){let localSwarm=path47.join(directory,".swarm"),now=Date.now(),cached2=_resolutionCache.get(directory);if(cached2&&now<cached2.expires)return cached2.linkDir??localSwarm;let linkDir=null;try{let pointer=readLinkPointer(directory);if(pointer){linkDir=path47.resolve(resolveLinkDir(pointer.linkId));let orphanStatus=getLinkedLocalKnowledgeStatus(directory);if(orphanStatus.orphaned)warn("[knowledge-link] local knowledge file is orphaned by link store",{localKnowledgePath:orphanStatus.localKnowledgePath,resolvedKnowledgePath:orphanStatus.resolvedKnowledgePath})}}catch{linkDir=null}if(!_resolutionCache.has(directory)&&_resolutionCache.size>=MAX_CACHE_ENTRIES2){let oldest=_resolutionCache.keys().next().value;if(oldest!==void 0)_resolutionCache.delete(oldest)}return _resolutionCache.set(directory,{linkDir,expires:now+CACHE_TTL_MS}),linkDir??localSwarm}function invalidateKnowledgeStoreDirCache(directory){if(directory===void 0){_resolutionCache.clear();return}_resolutionCache.delete(directory)}function isLinked(directory){return readLinkPointer(directory)!==null}var LINK_POINTER_FILENAME="link.json",MAX_LINK_ID_LENGTH=64,WINDOWS_RESERVED_NAMES,CACHE_TTL_MS=2000,MAX_CACHE_ENTRIES2=500,_resolutionCache;var init_knowledge_link=__esm(()=>{init_task_file();init_logger();WINDOWS_RESERVED_NAMES=new Set(["con","prn","aux","nul","com0","com1","com2","com3","com4","com5","com6","com7","com8","com9","lpt0","lpt1","lpt2","lpt3","lpt4","lpt5","lpt6","lpt7","lpt8","lpt9"]);_resolutionCache=new Map});import{execFile as execFile2}from"node:child_process";function markSuggested(sessionId){if(_suggestedSessions.has(sessionId))return;if(_suggestedSessions.size>=MAX_SUGGESTED_SESSIONS){let oldest=_suggestedSessions.values().next().value;if(oldest!==void 0)_suggestedSessions.delete(oldest)}_suggestedSessions.add(sessionId)}function countWorktrees(directory){return new Promise((resolve25)=>{try{let child=execFile2("git",["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS2,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve25(0);return}let count=0;for(let line of stdout.split(`
648
648
  `))if(line.startsWith("worktree "))count++;resolve25(count)});try{child.stdin?.end()}catch{}child.on("error",()=>resolve25(0))}catch{resolve25(0)}})}async function maybeSuggestWorktreeLink(directory,sessionId){try{if(!directory||!sessionId)return;if(_suggestedSessions.has(sessionId))return;if(markSuggested(sessionId),isLinked(directory))return;let worktrees=await countWorktrees(directory);if(worktrees>1)console.warn(`[opencode-swarm] Detected ${worktrees} git worktrees of this repo. Run \`/swarm link\` in each to share swarm knowledge across them (or \`/swarm link <name>\` to share with similar projects).`)}catch{}}var GIT_TIMEOUT_MS2=1500,MAX_SUGGESTED_SESSIONS=500,_suggestedSessions;var init_worktree_link_suggestion=__esm(()=>{init_knowledge_link();_suggestedSessions=new Set});class AgentRunContext{runId;activeToolCalls;activeAgent;delegationChains;agentSessions;environmentProfiles;toolAggregates;constructor(runId,toolAggregates){this.runId=runId,this.activeToolCalls=new Map,this.activeAgent=new Map,this.delegationChains=new Map,this.agentSessions=new Map,this.environmentProfiles=new Map,this.toolAggregates=toolAggregates}}var exports_pr_subscriptions={};__export(exports_pr_subscriptions,{updateSnapshot:()=>updateSnapshot,unsubscribe:()=>unsubscribe,sweepStale:()=>sweepStale,subscribe:()=>subscribe,setOnSubscriptionCreated:()=>setOnSubscriptionCreated,lookupByPr:()=>lookupByPr,listActive:()=>listActive,buildCorrelationId:()=>buildCorrelationId,PR_SUBSCRIPTIONS_FILE:()=>PR_SUBSCRIPTIONS_FILE});import*as fs22 from"node:fs";import*as path48 from"node:path";function setOnSubscriptionCreated(callback){onSubscriptionCreated=callback}function storePath2(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_FILE)}function ensureSwarmDir3(directory){fs22.mkdirSync(path48.resolve(directory,".swarm","pr-monitor"),{recursive:!0})}function buildCorrelationId(sessionID,repoFullName,prNumber){return`${sessionID}::${repoFullName}::${prNumber}`}function readAllRecords(directory){let raw;try{raw=fs22.readFileSync(storePath2(directory),"utf-8")}catch(err){if(err.code==="ENOENT")return[];return log(`[pr-monitor] readAllRecords failed: ${err instanceof Error?err.message:String(err)}`),[]}let folded=new Map;for(let line of raw.split(`
649
649
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{continue}let result=RecordSchema2.safeParse(parsedJson);if(!result.success)continue;folded.set(result.data.correlationId,result.data)}return[...folded.values()]}function appendRecord2(directory,record2){let result=RecordSchema2.safeParse(record2);if(!result.success)throw Error(`Invalid subscription record: ${result.error.message}`);ensureSwarmDir3(directory),fs22.appendFileSync(storePath2(directory),`${JSON.stringify(record2)}
650
- `,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord2(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord2(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord2(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateAgentEventTime:()=>updateAgentEventTime,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setCriticalShownIds:()=>setCriticalShownIds,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,pruneOldWindows:()=>pruneOldWindows,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,isCouncilGateActive:()=>isCouncilGateActive,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getRunContext:()=>getRunContext,getResolvedAutoProceed:()=>getResolvedAutoProceed,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,defaultRunContext:()=>defaultRunContext,clearCriticalShownIds:()=>clearCriticalShownIds,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,beginInvocation:()=>beginInvocation,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals26,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,AgentRunContext:()=>AgentRunContext});import*as fs23 from"node:fs/promises";import*as path49 from"node:path";function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetPct=0,swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope(),resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesThisCoderTask:[],turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals26.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals26.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){swarmState.agentSessions.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(session.modifiedFilesThisCoderTask===void 0)session.modifiedFilesThisCoderTask=[];if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals26.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName);if(stripped===ORCHESTRATOR_NAME)return null;let newId=(session.lastInvocationIdByAgent[stripped]||0)+1;session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),telemetry.delegationBegin(sessionId,stripped,session.currentTaskId??"unknown"),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function advanceTaskState(session,taskId,newState,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState}`);if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState),newState==="complete")session.stageBCompletion?.delete(taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState,current)}function canAdvanceTaskState(session,taskId,newState,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)return!1;if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState,directory,options,councilConfig){if(newState==="coder_delegated"){if(await isTaskSettled(directory,taskId)){warn(`[advanceTaskStateAndPersist] refusing to re-dispatch settled task ${taskId}; skipping in-memory advance + persist`);return}}if(advanceTaskState(session,taskId,newState,options,councilConfig),newState!=="coder_delegated"&&newState!=="complete")return;let planStatus=newState==="complete"?"completed":"in_progress";try{await updateTaskStatus(directory,taskId,planStatus,{force:!1})}catch(err){warn(`[advanceTaskStateAndPersist] persist ${taskId} → ${planStatus} failed (in-memory state still advanced): ${err instanceof Error?err.message:String(err)}`)}}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),profile=null;try{profile=getProfile(directory,planId)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);profile=null}if(!profile)return!1;let councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"coder_delegated";case"completed":return"complete";default:return"idle"}}function evidenceToWorkflowState(evidence){let gates=evidence.gates??{},requiredGates=evidence.required_gates??[];if(requiredGates.length>0){if(requiredGates.every((gate)=>gates[gate]!=null))return"complete"}if(gates.test_engineer!=null)return"tests_run";if(gates.reviewer!=null)return"reviewer_run";if(Object.keys(gates).length>0)return"coder_delegated";return"idle"}async function readPlanFromDisk(directory){try{let planPath=path49.join(directory,".swarm","plan.json"),content=await fs23.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path49.join(directory,".swarm","evidence"),entries=await fs23.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path49.join(evidenceDir,entry.name),content=await fs23.readFile(filePath,"utf-8"),parsed=JSON.parse(content);if(parsed&&typeof parsed.taskId==="string"&&Array.isArray(parsed.required_gates))evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory);_rehydrationCache={planTaskStates,evidenceMap}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedState=evidenceToWorkflowState(evidence),existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(derivedState)>existingIndex)session.taskWorkflowStates.set(taskId,derivedState)}else{let existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(planState)>existingIndex)session.taskWorkflowStates.set(taskId,planState)}}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){if(session.taskCouncilApproved.has(taskId))continue;let council=evidence.gates?.council;if(!council)continue;let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals26.buildRehydrationCache(directory),_internals26.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,_internals26;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_manager();init_utils3();init_trajectory_store();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"],_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,generatedAgentNames:[],lastBudgetPct:0,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};_internals26={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});async function handleAutoProceedCommand(_directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Auto-proceed requires an active session. Use /swarm auto-proceed from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Auto-proceed requires an active session to operate.";if(stripKnownSwarmPrefix(session.agentName)!=="architect")return`Error: Auto-proceed can only be toggled from the architect session. Currently active session is: ${session.agentName}`;let arg=args2[0]?.toLowerCase(),wasUndefinedBefore=session.autoProceedOverride===void 0,newAutoProceedOverride;if(arg==="on")newAutoProceedOverride=!0;else if(arg==="off")newAutoProceedOverride=!1;else if(arg===void 0)newAutoProceedOverride=!session.autoProceedOverride;else return'Error: Invalid argument for /swarm auto-proceed. Valid options: "on", "off", or omit the argument to toggle.';if(session.autoProceedOverride=newAutoProceedOverride,arg==="on"||arg==="off"||arg===void 0&&wasUndefinedBefore)session.autoProceedNudgeDone=!0;if(newAutoProceedOverride)return"Auto-proceed is now ON. Phase boundaries will advance automatically.";else return"Auto-proceed is now OFF. You will be asked before advancing to the next phase."}var init_auto_proceed=__esm(()=>{init_schema();init_state2()});import*as fs24 from"node:fs";import*as os13 from"node:os";import*as path50 from"node:path";function buildDelegationCostFields(input={}){let extracted=extractUsageAndCost(input.raw),usage=extracted.usage,model=extracted.model??input.model,reportedCost=extracted.cost_usd;if(reportedCost!==null)return{...usage,cost_usd:roundUsd(reportedCost),cost_source:"reported",model,gate:input.gate,retry_index:input.retry_index};let estimated=estimateCostUsd(usage,model,input.pricing);if(estimated!==null)return{...usage,cost_usd:roundUsd(estimated),cost_source:"estimated",model,gate:input.gate,retry_index:input.retry_index};return{...usage,cost_usd:null,cost_source:"unavailable",model,gate:input.gate,retry_index:input.retry_index}}function summarizeTelemetryCosts(directory){let summary=createEmptySummary();for(let event of readTelemetryEvents(directory)){if(event.event!=="delegation_end")continue;addDelegationEvent(summary,event)}return finalizeSummary(summary)}function readTelemetryEvents(directory){let swarmDir=path50.join(directory,".swarm"),files=[path50.join(swarmDir,"telemetry.jsonl.1"),path50.join(swarmDir,"telemetry.jsonl")],tmpDir=fs24.mkdtempSync(path50.join(os13.tmpdir(),"telemetry-snapshot-")),snapshotFiles=[];try{for(let file2 of files){if(!fs24.existsSync(file2))continue;let snap=path50.join(tmpDir,path50.basename(file2));try{fs24.copyFileSync(file2,snap),snapshotFiles.push(snap)}catch{}}}catch{}let events=[];for(let file2 of snapshotFiles){let content="";try{content=fs24.readFileSync(file2,"utf-8")}catch{continue}for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord(parsed))events.push(parsed)}catch{}}}try{for(let f of snapshotFiles)try{fs24.unlinkSync(f)}catch{}fs24.rmdirSync(tmpDir)}catch{}return events}function estimateCostUsd(usage,model,pricing){if(!model)return null;let table={...BUNDLED_MODEL_PRICING,...pricing?.models??{}},entry=table[model]??table[model.toLowerCase()];if(!entry)return null;let cost=usage.tokens_input/1e6*entry.input_per_million+usage.tokens_output/1e6*entry.output_per_million+usage.tokens_reasoning/1e6*(entry.reasoning_per_million??entry.output_per_million)+usage.tokens_cache/1e6*(entry.cache_per_million??entry.input_per_million);return cost>0?cost:null}function extractUsageAndCost(raw){let candidates=collectCandidateRecords(raw),usage={...ZERO_USAGE},cost_usd=null,model;for(let candidate of candidates){model??=readModelIdentifier(candidate),cost_usd??=readNumber(candidate,["cost_usd","total_cost_usd","cost","totalCost"]);let directInput=readNumber(candidate,["tokens_input","input_tokens","input","prompt_tokens"]),directOutput=readNumber(candidate,["tokens_output","output_tokens","output","completion_tokens"]),directReasoning=readNumber(candidate,["tokens_reasoning","reasoning_tokens","reasoning"]),directCache=readNumber(candidate,["tokens_cache","cache_tokens","cache_read_input_tokens","cached_input_tokens","cache_write_input_tokens","cache"]),nestedCache=readCacheTokens(candidate);usage.tokens_input||=directInput??0,usage.tokens_output||=directOutput??0,usage.tokens_reasoning||=directReasoning??0,usage.tokens_cache||=directCache??nestedCache??0}return{usage,cost_usd,model}}function collectCandidateRecords(raw){let records=[],visit=(value,depth)=>{if(depth>3||!isRecord(value))return;records.push(value);for(let key of["usage","tokens","cache","cost","metadata","data","info","message","assistant","task","part","response","output"])visit(value[key],depth+1)};return visit(raw,0),records}function readNumber(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value==="string"&&value.trim()!==""){let parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}return null}function readString(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="string"&&value.trim()!=="")return value.trim()}return}function readModelIdentifier(record2){let direct=readString(record2,["model","model_id"]);if(direct)return direct;let modelID=readString(record2,["modelID"]),providerID=readString(record2,["providerID"]);if(modelID&&providerID)return`${providerID}/${modelID}`;return modelID}function readCacheTokens(record2){let cacheRecord=isRecord(record2.cache)?record2.cache:record2,read=readNumber(cacheRecord,["read","cache_read_input_tokens"]),write=readNumber(cacheRecord,["write","cache_write_input_tokens","write_input_tokens"]);if(read===null&&write===null)return null;return(read??0)+(write??0)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function createEmptySummary(){return{total_cost_usd:0,total_reported_usd:0,total_estimated_usd:0,total_input_tokens:0,total_output_tokens:0,total_reasoning_tokens:0,total_cache_tokens:0,delegations:0,unavailable_delegations:0,by_agent:[],by_task:[],by_gate:[],by_retry:[],by_source:{reported:{delegations:0,cost_usd:0},estimated:{delegations:0,cost_usd:0},unavailable:{delegations:0,cost_usd:0}}}}function addDelegationEvent(summary,event){let costSource=parseCostSource(event.cost_source),cost=readNumber(event,["cost_usd"])??0,usage={tokens_input:readNumber(event,["tokens_input"])??0,tokens_output:readNumber(event,["tokens_output"])??0,tokens_reasoning:readNumber(event,["tokens_reasoning"])??0,tokens_cache:readNumber(event,["tokens_cache"])??0};if(summary.delegations++,summary.total_cost_usd+=cost,summary.total_input_tokens+=usage.tokens_input,summary.total_output_tokens+=usage.tokens_output,summary.total_reasoning_tokens+=usage.tokens_reasoning,summary.total_cache_tokens+=usage.tokens_cache,summary.by_source[costSource].delegations++,summary.by_source[costSource].cost_usd+=cost,costSource==="reported")summary.total_reported_usd+=cost;if(costSource==="estimated")summary.total_estimated_usd+=cost;if(costSource==="unavailable")summary.unavailable_delegations++;addRow(summary.by_agent,String(event.agentName??event.agent??"unknown"),{cost,costSource,usage}),addRow(summary.by_task,String(event.taskId??event.task_id??"unknown"),{cost,costSource,usage}),addRow(summary.by_gate,String(event.gate??"unknown"),{cost,costSource,usage}),addRow(summary.by_retry,String(readNumber(event,["retry_index","retryIndex"])??0),{cost,costSource,usage})}function addRow(rows,name,input){let row=rows.find((candidate)=>candidate.name===name);if(!row)row={name,delegations:0,cost_usd:0,input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_tokens:0,unavailable_delegations:0},rows.push(row);if(row.delegations++,row.cost_usd+=input.cost,row.input_tokens+=input.usage.tokens_input,row.output_tokens+=input.usage.tokens_output,row.reasoning_tokens+=input.usage.tokens_reasoning,row.cache_tokens+=input.usage.tokens_cache,input.costSource==="unavailable")row.unavailable_delegations++}function finalizeSummary(summary){summary.total_cost_usd=roundUsd(summary.total_cost_usd),summary.total_reported_usd=roundUsd(summary.total_reported_usd),summary.total_estimated_usd=roundUsd(summary.total_estimated_usd);for(let source of Object.values(summary.by_source))source.cost_usd=roundUsd(source.cost_usd);for(let rows of[summary.by_agent,summary.by_task,summary.by_gate,summary.by_retry]){for(let row of rows)row.cost_usd=roundUsd(row.cost_usd);rows.sort((a,b)=>b.cost_usd-a.cost_usd||b.delegations-a.delegations)}return summary}function parseCostSource(value){return value==="reported"||value==="estimated"||value==="unavailable"?value:"unavailable"}function roundUsd(value){return Math.round(value*1e6)/1e6}var ZERO_USAGE,BUNDLED_MODEL_PRICING;var init_cost_accounting=__esm(()=>{ZERO_USAGE={tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0},BUNDLED_MODEL_PRICING={}});async function handleBenchmarkCommand(directory,args2){let cumulative=args2.includes("--cumulative");if(args2.includes("--ci-gate"))cumulative=!0;let maxCostUsd=parseMaxCostUsd(args2),mode=cumulative?"cumulative":"in-memory",costSummary=cumulative?summarizeTelemetryCosts(directory):void 0,agentMap=new Map;for(let[,s]of swarmState.agentSessions){let e=agentMap.get(s.agentName)||{toolCalls:0,hardLimits:0,warnings:0},windows=Object.values(s.windows);e.toolCalls+=windows.reduce((sum,w)=>sum+w.toolCalls,0),e.hardLimits+=windows.filter((w)=>w.hardLimitHit).length,e.warnings+=windows.filter((w)=>w.warningIssued).length,agentMap.set(s.agentName,e)}let agentHealth=Array.from(agentMap.entries()).map(([a,v])=>({agent:a,...v})),toolPerf=[];for(let[,a]of swarmState.toolAggregates){let successRate=a.count?a.successCount/a.count*100:0;toolPerf.push({tool:a.tool,calls:a.count,successRate:Math.round(successRate*10)/10,avg:a.count?Math.round(a.totalDuration/a.count):0})}toolPerf.sort((a,b)=>b.calls-a.calls);let delegationCount=0;for(let c of swarmState.delegationChains.values())delegationCount+=c.length;let quality,qualityMetrics;if(cumulative){let reviewPasses=0,reviewFails=0,testPasses=0,testFails=0,additions=0,deletions=0,totalComplexityDelta=0,totalPublicApiDelta=0,totalDuplicationRatio=0,totalTestToCodeRatio=0,qualityEvidenceCount=0;for(let tid of await listEvidenceTaskIds(directory)){let result;try{result=await loadEvidence(directory,tid)}catch(_evidenceErr){warn("benchmark: skipping corrupt or unreadable evidence for task",tid);continue}if(result.status!=="found")continue;for(let e of result.bundle.entries){if(!isValidEvidenceType(e.type)){warn(`Unknown evidence type '${e.type}' in task ${tid}, skipping`);continue}if(e.type==="review"){if(e.verdict==="approved")reviewPasses++;else if(e.verdict==="rejected")reviewFails++}else if(e.type==="test")testPasses+=e.tests_passed,testFails+=e.tests_failed;else if(e.type==="diff")additions+=e.additions,deletions+=e.deletions;else if(e.type==="quality_budget"){let qe=e;totalComplexityDelta+=qe.metrics.complexity_delta,totalPublicApiDelta+=qe.metrics.public_api_delta,totalDuplicationRatio+=qe.metrics.duplication_ratio*100,totalTestToCodeRatio+=qe.metrics.test_to_code_ratio*100,qualityEvidenceCount++}}}let totalReviews=reviewPasses+reviewFails,totalTests=testPasses+testFails;if(quality={reviewPassRate:totalReviews?Math.round(reviewPasses/totalReviews*1000)/10:null,testPassRate:totalTests?Math.round(testPasses/totalTests*1000)/10:null,totalReviews,testsPassed:testPasses,testsFailed:testFails,additions,deletions},qualityEvidenceCount>0)qualityMetrics={complexityDelta:Math.round(totalComplexityDelta/qualityEvidenceCount*10)/10,publicApiDelta:Math.round(totalPublicApiDelta/qualityEvidenceCount*10)/10,duplicationRatio:Math.round(totalDuplicationRatio/qualityEvidenceCount*10)/10,testToCodeRatio:Math.round(totalTestToCodeRatio/qualityEvidenceCount*10)/10,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!0};else qualityMetrics={complexityDelta:0,publicApiDelta:0,duplicationRatio:0,testToCodeRatio:0,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!1}}let ciGate;if(args2.includes("--ci-gate")){let totalCalls=0,totalFailures=0;for(let[,a]of swarmState.toolAggregates)totalCalls+=a.count,totalFailures+=a.failureCount;let agentErrorRate=totalCalls?totalFailures/totalCalls*100:0,maxHardLimits=0;for(let v of agentMap.values())if(v.hardLimits>maxHardLimits)maxHardLimits=v.hardLimits;let hasQualityEvidence=qualityMetrics?.hasEvidence??!1,complexityDelta=qualityMetrics?.complexityDelta??0,publicApiDelta=qualityMetrics?.publicApiDelta??0,duplicationRatio=qualityMetrics?.duplicationRatio??0,testToCodeRatio=qualityMetrics?.testToCodeRatio??0,checks3=[{name:"Review pass rate",value:quality?.reviewPassRate??0,threshold:CI.review_pass_rate,operator:">=",passed:(quality?.reviewPassRate??0)>=CI.review_pass_rate},{name:"Test pass rate",value:quality?.testPassRate??0,threshold:CI.test_pass_rate,operator:">=",passed:(quality?.testPassRate??0)>=CI.test_pass_rate},{name:"Agent error rate",value:Math.round(agentErrorRate*10)/10,threshold:CI.max_agent_error_rate,operator:"<=",passed:agentErrorRate<=CI.max_agent_error_rate},{name:"Hard limit hits",value:maxHardLimits,threshold:CI.max_hard_limit_hits,operator:"<=",passed:maxHardLimits<=CI.max_hard_limit_hits},{name:"Complexity Delta",value:complexityDelta,threshold:CI.max_complexity_delta,operator:"<=",passed:!hasQualityEvidence||complexityDelta<=CI.max_complexity_delta},{name:"Public API Delta",value:publicApiDelta,threshold:CI.max_public_api_delta,operator:"<=",passed:!hasQualityEvidence||publicApiDelta<=CI.max_public_api_delta},{name:"Duplication Ratio",value:duplicationRatio,threshold:CI.max_duplication_ratio,operator:"<=",passed:!hasQualityEvidence||duplicationRatio<=CI.max_duplication_ratio},{name:"Test-to-Code Ratio",value:testToCodeRatio,threshold:CI.min_test_to_code_ratio,operator:">=",passed:!hasQualityEvidence||testToCodeRatio>=CI.min_test_to_code_ratio}];if(maxCostUsd!==null)checks3.push({name:"Total cost",value:costSummary?.total_cost_usd??0,threshold:maxCostUsd,operator:"<=",passed:(costSummary?.total_cost_usd??0)<=maxCostUsd});ciGate={passed:checks3.every((c)=>c.passed),checks:checks3}}let lines=[`## Swarm Benchmark (mode: ${mode})`,"","### Agent Health"];if(!agentHealth.length)lines.push("No agent sessions recorded");else for(let{agent,toolCalls,hardLimits,warnings}of agentHealth){let parts=[`${toolCalls} tool calls`];if(warnings>0)parts.push(`${warnings} warning${warnings>1?"s":""}`);parts.push(hardLimits?`${hardLimits} hard limit hit${hardLimits>1?"s":""}`:"0 hard limits"),lines.push(`- ${hardLimits?"⚠️":"✅"} **${agent}**: ${parts.join(", ")}`)}if(lines.push("","### Tool Performance"),!toolPerf.length)lines.push("No tool data recorded");else{lines.push("| Tool | Calls | Success Rate | Avg Duration |","|------|-------|-------------|-------------|");for(let{tool,calls,successRate,avg}of toolPerf)lines.push(`| ${tool} | ${calls} | ${successRate}% | ${avg}ms |`)}if(lines.push("","### Delegations",delegationCount?`Total: ${delegationCount} delegations`:"No delegations recorded",""),quality){if(lines.push("### Quality Signals"),!quality.totalReviews&&!quality.testsPassed&&!quality.additions)lines.push("No evidence data found");else{if(quality.reviewPassRate!==null)lines.push(`- Review pass rate: ${quality.reviewPassRate}% (${quality.totalReviews}) ${quality.reviewPassRate>=70?"✅":"❌"}`);else lines.push("- Review pass rate: N/A (no reviews)");if(quality.testPassRate!==null)lines.push(`- Test pass rate: ${quality.testPassRate}% (${quality.testsPassed}/${quality.testsPassed+quality.testsFailed}) ${quality.testPassRate>=80?"✅":"❌"}`);else lines.push("- Test pass rate: N/A (no tests)");lines.push(`- Code churn: +${quality.additions} / -${quality.deletions} lines`)}lines.push("")}if(qualityMetrics?.hasEvidence)lines.push("### Quality Metrics"),lines.push(`- Complexity Delta: ${qualityMetrics.complexityDelta} (max: ${qualityMetrics.thresholds.maxComplexityDelta}) ${qualityMetrics.complexityDelta<=qualityMetrics.thresholds.maxComplexityDelta?"✅":"❌"}`),lines.push(`- Public API Delta: ${qualityMetrics.publicApiDelta} (max: ${qualityMetrics.thresholds.maxPublicApiDelta}) ${qualityMetrics.publicApiDelta<=qualityMetrics.thresholds.maxPublicApiDelta?"✅":"❌"}`),lines.push(`- Duplication Ratio: ${qualityMetrics.duplicationRatio}% (max: ${qualityMetrics.thresholds.maxDuplicationRatio}%) ${qualityMetrics.duplicationRatio<=qualityMetrics.thresholds.maxDuplicationRatio?"✅":"❌"}`),lines.push(`- Test-to-Code Ratio: ${qualityMetrics.testToCodeRatio}% (min: ${qualityMetrics.thresholds.minTestToCodeRatio}%) ${qualityMetrics.testToCodeRatio>=qualityMetrics.thresholds.minTestToCodeRatio?"✅":"❌"}`),lines.push("");if(costSummary)lines.push("### Cost Signals"),lines.push(`- Total tracked cost: $${costSummary.total_cost_usd.toFixed(6)} (${costSummary.delegations} delegations)`,`- Reported: $${costSummary.total_reported_usd.toFixed(6)}; estimated: $${costSummary.total_estimated_usd.toFixed(6)}; unavailable: ${costSummary.unavailable_delegations}`),lines.push("");if(ciGate){lines.push("### CI Gate",ciGate.passed?"✅ PASSED":"❌ FAILED");for(let c of ciGate.checks){let valueStr;if(c.name==="Complexity Delta"||c.name==="Public API Delta")valueStr=`${c.value}`;else if(c.name==="Total cost")valueStr=`$${c.value.toFixed(6)}`;else valueStr=`${c.value}%`;let thresholdStr=c.name==="Complexity Delta"||c.name==="Public API Delta"?`${c.threshold}`:c.name==="Total cost"?`$${c.threshold.toFixed(6)}`:`${c.threshold}%`;lines.push(`- ${c.name}: ${valueStr} ${c.operator} ${thresholdStr} ${c.passed?"✅":"❌"}`)}lines.push("")}let json2={mode,timestamp:new Date().toISOString(),agent_health:agentHealth.map((a)=>({agent:a.agent,tool_calls:a.toolCalls,hard_limit_hits:a.hardLimits,warnings:a.warnings})),tool_performance:toolPerf.map((t)=>({tool:t.tool,calls:t.calls,success_rate:t.successRate,avg_duration_ms:t.avg})),delegations:delegationCount};if(quality)json2.quality={review_pass_rate:quality.reviewPassRate,test_pass_rate:quality.testPassRate,total_reviews:quality.totalReviews,total_tests_passed:quality.testsPassed,total_tests_failed:quality.testsFailed,additions:quality.additions,deletions:quality.deletions};if(qualityMetrics)json2.quality_metrics={complexity_delta:qualityMetrics.complexityDelta,public_api_delta:qualityMetrics.publicApiDelta,duplication_ratio:qualityMetrics.duplicationRatio,test_to_code_ratio:qualityMetrics.testToCodeRatio,thresholds:qualityMetrics.thresholds,has_evidence:qualityMetrics.hasEvidence};if(costSummary)json2.costs={total_cost_usd:costSummary.total_cost_usd,total_reported_usd:costSummary.total_reported_usd,total_estimated_usd:costSummary.total_estimated_usd,total_input_tokens:costSummary.total_input_tokens,total_output_tokens:costSummary.total_output_tokens,total_reasoning_tokens:costSummary.total_reasoning_tokens,total_cache_tokens:costSummary.total_cache_tokens,delegations:costSummary.delegations,unavailable_delegations:costSummary.unavailable_delegations};if(ciGate)json2.ci_gate={passed:ciGate.passed,checks:ciGate.checks.map((c)=>({name:c.name,value:c.value,threshold:c.threshold,operator:c.operator,passed:c.passed}))};return lines.push("[BENCHMARK_JSON]",JSON.stringify(json2,null,2),"[/BENCHMARK_JSON]"),lines.join(`
650
+ `,"utf-8")}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let existing=readAllRecords(directory),match=existing.find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),match;if(input.maxSubscriptions!==void 0&&input.maxSubscriptions>0){let activeCount=existing.filter((r)=>r.status==="active").length;if(activeCount>=input.maxSubscriptions)throw Error(`PR subscription limit reached: ${activeCount}/${input.maxSubscriptions}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return appendRecord2(directory,record2),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return appendRecord2(directory,removed),removed})}async function listActive(directory){return readAllRecords(directory).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){for(let record2 of readAllRecords(directory))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let match=readAllRecords(directory).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return null;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return appendRecord2(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let swept=0;for(let record2 of readAllRecords(directory)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord2(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now}),swept+=1,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",STORE_LOCK_AGENT2="pr-monitor",STORE_LOCK_TASK2="pr-subscriptions",onSubscriptionCreated=null,RecordSchema2;var init_pr_subscriptions=__esm(()=>{init_zod();init_lock();init_utils2();init_utils();RecordSchema2=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict()});var exports_state={};__export(exports_state,{updateAgentEventTime:()=>updateAgentEventTime,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setCriticalShownIds:()=>setCriticalShownIds,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,pruneOldWindows:()=>pruneOldWindows,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,isCouncilGateActive:()=>isCouncilGateActive,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getRunContext:()=>getRunContext,getResolvedAutoProceed:()=>getResolvedAutoProceed,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,defaultRunContext:()=>defaultRunContext,clearCriticalShownIds:()=>clearCriticalShownIds,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,beginInvocation:()=>beginInvocation,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals26,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,AgentRunContext:()=>AgentRunContext});import*as fs23 from"node:fs/promises";import*as path49 from"node:path";function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetPct=0,swarmState.agentSessions.clear(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope(),resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now()){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();sweepStaleSessions(staleDurationMs,now);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesThisCoderTask:[],turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals26.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals26.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId){swarmState.agentSessions.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now(),session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(session.modifiedFilesThisCoderTask===void 0)session.modifiedFilesThisCoderTask=[];if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(),session}if(_internals26.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName);if(stripped===ORCHESTRATOR_NAME)return null;let newId=(session.lastInvocationIdByAgent[stripped]||0)+1;session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),telemetry.delegationBegin(sessionId,stripped,session.currentTaskId??"unknown"),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function advanceTaskState(session,taskId,newState,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState}`);if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState),newState==="complete")session.stageBCompletion?.delete(taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState,current)}function canAdvanceTaskState(session,taskId,newState,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=STATE_ORDER.indexOf(current);if(STATE_ORDER.indexOf(newState)<=currentIndex)return!1;if(newState==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState,directory,options,councilConfig){if(newState==="coder_delegated"){if(await isTaskSettled(directory,taskId)){warn(`[advanceTaskStateAndPersist] refusing to re-dispatch settled task ${taskId}; skipping in-memory advance + persist`);return}}if(advanceTaskState(session,taskId,newState,options,councilConfig),newState!=="coder_delegated"&&newState!=="complete")return;let planStatus=newState==="complete"?"completed":"in_progress";try{await updateTaskStatus(directory,taskId,planStatus,{force:!1})}catch(err){warn(`[advanceTaskStateAndPersist] persist ${taskId} → ${planStatus} failed (in-memory state still advanced): ${err instanceof Error?err.message:String(err)}`)}}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),profile=null;try{profile=getProfile(directory,planId)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);profile=null}if(!profile)return!1;let councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"coder_delegated";case"completed":return"complete";default:return"idle"}}function evidenceToWorkflowState(evidence){let gates=evidence.gates??{},requiredGates=evidence.required_gates??[];if(requiredGates.length>0){if(requiredGates.every((gate)=>gates[gate]!=null))return"complete"}if(gates.test_engineer!=null)return"tests_run";if(gates.reviewer!=null)return"reviewer_run";if(Object.keys(gates).length>0)return"coder_delegated";return"idle"}async function readPlanFromDisk(directory){try{let planPath=path49.join(directory,".swarm","plan.json"),content=await fs23.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path49.join(directory,".swarm","evidence"),entries=await fs23.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path49.join(evidenceDir,entry.name),content=await fs23.readFile(filePath,"utf-8"),parsed=JSON.parse(content);if(parsed&&typeof parsed.taskId==="string"&&Array.isArray(parsed.required_gates))evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory);_rehydrationCache={planTaskStates,evidenceMap}}function applyRehydrationCache(session){if(!_rehydrationCache)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap}=_rehydrationCache;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedState=evidenceToWorkflowState(evidence),existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(derivedState)>existingIndex)session.taskWorkflowStates.set(taskId,derivedState)}else{let existingIndex=existingState?STATE_ORDER.indexOf(existingState):-1;if(STATE_ORDER.indexOf(planState)>existingIndex)session.taskWorkflowStates.set(taskId,planState)}}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){if(session.taskCouncilApproved.has(taskId))continue;let council=evidence.gates?.council;if(!council)continue;let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals26.buildRehydrationCache(directory),_internals26.applyRehydrationCache(session)}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function addKnowledgeAckDedup(key){let set2=swarmState.knowledgeAckDedup;if(set2.has(key))return;if(set2.add(key),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _rehydrationCache=null,_councilDisagreementWarned,STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,_internals26;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_manager();init_utils3();init_trajectory_store();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"],_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,generatedAgentNames:[],lastBudgetPct:0,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};_internals26={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});async function handleAutoProceedCommand(_directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Auto-proceed requires an active session. Use /swarm auto-proceed from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Auto-proceed requires an active session to operate.";if(stripKnownSwarmPrefix(session.agentName)!=="architect")return`Error: Auto-proceed can only be toggled from the architect session. Currently active session is: ${session.agentName}`;let arg=args2[0]?.toLowerCase(),wasUndefinedBefore=session.autoProceedOverride===void 0,newAutoProceedOverride;if(arg==="on")newAutoProceedOverride=!0;else if(arg==="off")newAutoProceedOverride=!1;else if(arg===void 0)newAutoProceedOverride=!session.autoProceedOverride;else return'Error: Invalid argument for /swarm auto-proceed. Valid options: "on", "off", or omit the argument to toggle.';if(session.autoProceedOverride=newAutoProceedOverride,arg==="on"||arg==="off"||arg===void 0&&wasUndefinedBefore)session.autoProceedNudgeDone=!0;if(newAutoProceedOverride)return"Auto-proceed is now ON. Phase boundaries will advance automatically.";else return"Auto-proceed is now OFF. You will be asked before advancing to the next phase."}var init_auto_proceed=__esm(()=>{init_schema();init_state2()});import*as fs24 from"node:fs";import*as os13 from"node:os";import*as path50 from"node:path";function buildDelegationCostFields(input={}){let extracted=extractUsageAndCost(input.raw),usage=extracted.usage,model=extracted.model??input.model,reportedCost=extracted.cost_usd;if(reportedCost!==null)return{...usage,cost_usd:roundUsd(reportedCost),cost_source:"reported",model,gate:input.gate,retry_index:input.retry_index};let estimated=estimateCostUsd(usage,model,input.pricing);if(estimated!==null)return{...usage,cost_usd:roundUsd(estimated),cost_source:"estimated",model,gate:input.gate,retry_index:input.retry_index};return{...usage,cost_usd:null,cost_source:"unavailable",model,gate:input.gate,retry_index:input.retry_index}}function summarizeTelemetryCosts(directory){let summary=createEmptySummary();for(let event of readTelemetryEvents(directory)){if(event.event!=="delegation_end")continue;addDelegationEvent(summary,event)}return finalizeSummary(summary)}function readTelemetryEvents(directory){let swarmDir=path50.join(directory,".swarm"),files=[path50.join(swarmDir,"telemetry.jsonl.1"),path50.join(swarmDir,"telemetry.jsonl")],tmpDir=fs24.mkdtempSync(path50.join(os13.tmpdir(),"telemetry-snapshot-")),snapshotFiles=[];try{for(let file2 of files){if(!fs24.existsSync(file2))continue;let snap=path50.join(tmpDir,path50.basename(file2));try{fs24.copyFileSync(file2,snap),snapshotFiles.push(snap)}catch{}}}catch{}let events=[];for(let file2 of snapshotFiles){let content="";try{content=fs24.readFileSync(file2,"utf-8")}catch{continue}for(let line of content.split(/\r?\n/)){let trimmed=line.trim();if(!trimmed)continue;try{let parsed=JSON.parse(trimmed);if(isRecord(parsed))events.push(parsed)}catch{}}}try{for(let f of snapshotFiles)try{fs24.unlinkSync(f)}catch{}fs24.rmdirSync(tmpDir)}catch{}return events}function estimateCostUsd(usage,model,pricing){if(!model)return null;let table={...BUNDLED_MODEL_PRICING,...pricing?.models??{}},entry=table[model]??table[model.toLowerCase()];if(!entry)return null;let cost=usage.tokens_input/1e6*entry.input_per_million+usage.tokens_output/1e6*entry.output_per_million+usage.tokens_reasoning/1e6*(entry.reasoning_per_million??entry.output_per_million)+usage.tokens_cache/1e6*(entry.cache_per_million??entry.input_per_million);return cost>0?cost:null}function extractUsageAndCost(raw){let candidates=collectCandidateRecords(raw),usage={...ZERO_USAGE},cost_usd=null,model;for(let candidate of candidates){model??=readModelIdentifier(candidate),cost_usd??=readNumber(candidate,["cost_usd","total_cost_usd","cost","totalCost"]);let directInput=readNumber(candidate,["tokens_input","input_tokens","input","prompt_tokens"]),directOutput=readNumber(candidate,["tokens_output","output_tokens","output","completion_tokens"]),directReasoning=readNumber(candidate,["tokens_reasoning","reasoning_tokens","reasoning"]),directCache=readNumber(candidate,["tokens_cache","cache_tokens","cache_read_input_tokens","cached_input_tokens","cache_write_input_tokens","cache"]),nestedCache=readCacheTokens(candidate);usage.tokens_input||=directInput??0,usage.tokens_output||=directOutput??0,usage.tokens_reasoning||=directReasoning??0,usage.tokens_cache||=directCache??nestedCache??0}return{usage,cost_usd,model}}function collectCandidateRecords(raw){let records=[],visit=(value,depth)=>{if(depth>3||!isRecord(value))return;records.push(value);for(let key of["usage","tokens","cache","cost","metadata","data","info","message","assistant","task","part","response","output"])visit(value[key],depth+1)};return visit(raw,0),records}function readNumber(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="number"&&Number.isFinite(value)&&value>=0)return value;if(typeof value==="string"&&value.trim()!==""){let parsed=Number(value);if(Number.isFinite(parsed)&&parsed>=0)return parsed}}return null}function readString(record2,keys){for(let key of keys){let value=record2[key];if(typeof value==="string"&&value.trim()!=="")return value.trim()}return}function readModelIdentifier(record2){let direct=readString(record2,["model","model_id"]);if(direct)return direct;let modelID=readString(record2,["modelID"]),providerID=readString(record2,["providerID"]);if(modelID&&providerID)return`${providerID}/${modelID}`;return modelID}function readCacheTokens(record2){let cacheRecord=isRecord(record2.cache)?record2.cache:record2,read=readNumber(cacheRecord,["read","cache_read_input_tokens"]),write=readNumber(cacheRecord,["write","cache_write_input_tokens","write_input_tokens"]);if(read===null&&write===null)return null;return(read??0)+(write??0)}function isRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}function createEmptySummary(){return{total_cost_usd:0,total_reported_usd:0,total_estimated_usd:0,total_input_tokens:0,total_output_tokens:0,total_reasoning_tokens:0,total_cache_tokens:0,delegations:0,unavailable_delegations:0,by_agent:[],by_task:[],by_gate:[],by_retry:[],by_source:{reported:{delegations:0,cost_usd:0},estimated:{delegations:0,cost_usd:0},unavailable:{delegations:0,cost_usd:0}}}}function addDelegationEvent(summary,event){let costSource=parseCostSource(event.cost_source),cost=readNumber(event,["cost_usd"])??0,usage={tokens_input:readNumber(event,["tokens_input"])??0,tokens_output:readNumber(event,["tokens_output"])??0,tokens_reasoning:readNumber(event,["tokens_reasoning"])??0,tokens_cache:readNumber(event,["tokens_cache"])??0};if(summary.delegations++,summary.total_cost_usd+=cost,summary.total_input_tokens+=usage.tokens_input,summary.total_output_tokens+=usage.tokens_output,summary.total_reasoning_tokens+=usage.tokens_reasoning,summary.total_cache_tokens+=usage.tokens_cache,summary.by_source[costSource].delegations++,summary.by_source[costSource].cost_usd+=cost,costSource==="reported")summary.total_reported_usd+=cost;if(costSource==="estimated")summary.total_estimated_usd+=cost;if(costSource==="unavailable")summary.unavailable_delegations++;addRow(summary.by_agent,String(event.agentName??event.agent??"unknown"),{cost,costSource,usage}),addRow(summary.by_task,String(event.taskId??event.task_id??"unknown"),{cost,costSource,usage}),addRow(summary.by_gate,String(event.gate??"unknown"),{cost,costSource,usage}),addRow(summary.by_retry,String(readNumber(event,["retry_index","retryIndex"])??0),{cost,costSource,usage})}function addRow(rows,name,input){let row=rows.find((candidate)=>candidate.name===name);if(!row)row={name,delegations:0,cost_usd:0,input_tokens:0,output_tokens:0,reasoning_tokens:0,cache_tokens:0,unavailable_delegations:0},rows.push(row);if(row.delegations++,row.cost_usd+=input.cost,row.input_tokens+=input.usage.tokens_input,row.output_tokens+=input.usage.tokens_output,row.reasoning_tokens+=input.usage.tokens_reasoning,row.cache_tokens+=input.usage.tokens_cache,input.costSource==="unavailable")row.unavailable_delegations++}function finalizeSummary(summary){summary.total_cost_usd=roundUsd(summary.total_cost_usd),summary.total_reported_usd=roundUsd(summary.total_reported_usd),summary.total_estimated_usd=roundUsd(summary.total_estimated_usd);for(let source of Object.values(summary.by_source))source.cost_usd=roundUsd(source.cost_usd);for(let rows of[summary.by_agent,summary.by_task,summary.by_gate,summary.by_retry]){for(let row of rows)row.cost_usd=roundUsd(row.cost_usd);rows.sort((a,b)=>b.cost_usd-a.cost_usd||b.delegations-a.delegations)}return summary}function parseCostSource(value){return value==="reported"||value==="estimated"||value==="unavailable"?value:"unavailable"}function roundUsd(value){return Math.round(value*1e6)/1e6}var ZERO_USAGE,BUNDLED_MODEL_PRICING;var init_cost_accounting=__esm(()=>{ZERO_USAGE={tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0},BUNDLED_MODEL_PRICING={}});async function handleBenchmarkCommand(directory,args2){let cumulative=args2.includes("--cumulative");if(args2.includes("--ci-gate"))cumulative=!0;let maxCostUsd=parseMaxCostUsd(args2),mode=cumulative?"cumulative":"in-memory",costSummary=cumulative?summarizeTelemetryCosts(directory):void 0,agentMap=new Map;for(let[,s]of swarmState.agentSessions){let e=agentMap.get(s.agentName)||{toolCalls:0,hardLimits:0,warnings:0},windows=Object.values(s.windows);e.toolCalls+=windows.reduce((sum,w)=>sum+w.toolCalls,0),e.hardLimits+=windows.filter((w)=>w.hardLimitHit).length,e.warnings+=windows.filter((w)=>w.warningIssued).length,agentMap.set(s.agentName,e)}let agentHealth=Array.from(agentMap.entries()).map(([a,v])=>({agent:a,...v})),toolPerf=[];for(let[,a]of swarmState.toolAggregates){let successRate=a.count?a.successCount/a.count*100:0;toolPerf.push({tool:a.tool,calls:a.count,successRate:Math.round(successRate*10)/10,avg:a.count?Math.round(a.totalDuration/a.count):0})}toolPerf.sort((a,b)=>b.calls-a.calls);let delegationCount=0;for(let c of swarmState.delegationChains.values())delegationCount+=c.length;let quality,qualityMetrics;if(cumulative){let reviewPasses=0,reviewFails=0,testPasses=0,testFails=0,additions=0,deletions=0,totalComplexityDelta=0,totalPublicApiDelta=0,totalDuplicationRatio=0,totalTestToCodeRatio=0,qualityEvidenceCount=0;for(let tid of await listEvidenceTaskIds(directory)){let result;try{result=await loadEvidence(directory,tid)}catch(_evidenceErr){warn("benchmark: skipping corrupt or unreadable evidence for task",tid);continue}if(result.status!=="found")continue;for(let e of result.bundle.entries){if(!isValidEvidenceType(e.type)){warn(`Unknown evidence type '${e.type}' in task ${tid}, skipping`);continue}if(e.type==="review"){if(e.verdict==="approved")reviewPasses++;else if(e.verdict==="rejected")reviewFails++}else if(e.type==="test")testPasses+=e.tests_passed,testFails+=e.tests_failed;else if(e.type==="diff")additions+=e.additions,deletions+=e.deletions;else if(e.type==="quality_budget"){let qe=e;totalComplexityDelta+=qe.metrics.complexity_delta,totalPublicApiDelta+=qe.metrics.public_api_delta,totalDuplicationRatio+=qe.metrics.duplication_ratio*100,totalTestToCodeRatio+=qe.metrics.test_to_code_ratio*100,qualityEvidenceCount++}}}let totalReviews=reviewPasses+reviewFails,totalTests=testPasses+testFails;if(quality={reviewPassRate:totalReviews?Math.round(reviewPasses/totalReviews*1000)/10:null,testPassRate:totalTests?Math.round(testPasses/totalTests*1000)/10:null,totalReviews,testsPassed:testPasses,testsFailed:testFails,additions,deletions},qualityEvidenceCount>0)qualityMetrics={complexityDelta:Math.round(totalComplexityDelta/qualityEvidenceCount*10)/10,publicApiDelta:Math.round(totalPublicApiDelta/qualityEvidenceCount*10)/10,duplicationRatio:Math.round(totalDuplicationRatio/qualityEvidenceCount*10)/10,testToCodeRatio:Math.round(totalTestToCodeRatio/qualityEvidenceCount*10)/10,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!0};else qualityMetrics={complexityDelta:0,publicApiDelta:0,duplicationRatio:0,testToCodeRatio:0,thresholds:{maxComplexityDelta:CI.max_complexity_delta,maxPublicApiDelta:CI.max_public_api_delta,maxDuplicationRatio:CI.max_duplication_ratio,minTestToCodeRatio:CI.min_test_to_code_ratio},hasEvidence:!1}}let ciGate;if(args2.includes("--ci-gate")){let totalCalls=0,totalFailures=0;for(let[,a]of swarmState.toolAggregates)totalCalls+=a.count,totalFailures+=a.failureCount;let agentErrorRate=totalCalls?totalFailures/totalCalls*100:0,maxHardLimits=0;for(let v of agentMap.values())if(v.hardLimits>maxHardLimits)maxHardLimits=v.hardLimits;let hasQualityEvidence=qualityMetrics?.hasEvidence??!1,complexityDelta=qualityMetrics?.complexityDelta??0,publicApiDelta=qualityMetrics?.publicApiDelta??0,duplicationRatio=qualityMetrics?.duplicationRatio??0,testToCodeRatio=qualityMetrics?.testToCodeRatio??0,checks3=[{name:"Review pass rate",value:quality?.reviewPassRate??0,threshold:CI.review_pass_rate,operator:">=",passed:(quality?.reviewPassRate??0)>=CI.review_pass_rate},{name:"Test pass rate",value:quality?.testPassRate??0,threshold:CI.test_pass_rate,operator:">=",passed:(quality?.testPassRate??0)>=CI.test_pass_rate},{name:"Agent error rate",value:Math.round(agentErrorRate*10)/10,threshold:CI.max_agent_error_rate,operator:"<=",passed:agentErrorRate<=CI.max_agent_error_rate},{name:"Hard limit hits",value:maxHardLimits,threshold:CI.max_hard_limit_hits,operator:"<=",passed:maxHardLimits<=CI.max_hard_limit_hits},{name:"Complexity Delta",value:complexityDelta,threshold:CI.max_complexity_delta,operator:"<=",passed:!hasQualityEvidence||complexityDelta<=CI.max_complexity_delta},{name:"Public API Delta",value:publicApiDelta,threshold:CI.max_public_api_delta,operator:"<=",passed:!hasQualityEvidence||publicApiDelta<=CI.max_public_api_delta},{name:"Duplication Ratio",value:duplicationRatio,threshold:CI.max_duplication_ratio,operator:"<=",passed:!hasQualityEvidence||duplicationRatio<=CI.max_duplication_ratio},{name:"Test-to-Code Ratio",value:testToCodeRatio,threshold:CI.min_test_to_code_ratio,operator:">=",passed:!hasQualityEvidence||testToCodeRatio>=CI.min_test_to_code_ratio}];if(maxCostUsd!==null)checks3.push({name:"Total cost",value:costSummary?.total_cost_usd??0,threshold:maxCostUsd,operator:"<=",passed:(costSummary?.total_cost_usd??0)<=maxCostUsd});ciGate={passed:checks3.every((c)=>c.passed),checks:checks3}}let lines=[`## Swarm Benchmark (mode: ${mode})`,"","### Agent Health"];if(!agentHealth.length)lines.push("No agent sessions recorded");else for(let{agent,toolCalls,hardLimits,warnings}of agentHealth){let parts=[`${toolCalls} tool calls`];if(warnings>0)parts.push(`${warnings} warning${warnings>1?"s":""}`);parts.push(hardLimits?`${hardLimits} hard limit hit${hardLimits>1?"s":""}`:"0 hard limits"),lines.push(`- ${hardLimits?"⚠️":"✅"} **${agent}**: ${parts.join(", ")}`)}if(lines.push("","### Tool Performance"),!toolPerf.length)lines.push("No tool data recorded");else{lines.push("| Tool | Calls | Success Rate | Avg Duration |","|------|-------|-------------|-------------|");for(let{tool,calls,successRate,avg}of toolPerf)lines.push(`| ${tool} | ${calls} | ${successRate}% | ${avg}ms |`)}if(lines.push("","### Delegations",delegationCount?`Total: ${delegationCount} delegations`:"No delegations recorded",""),quality){if(lines.push("### Quality Signals"),!quality.totalReviews&&!quality.testsPassed&&!quality.additions)lines.push("No evidence data found");else{if(quality.reviewPassRate!==null)lines.push(`- Review pass rate: ${quality.reviewPassRate}% (${quality.totalReviews}) ${quality.reviewPassRate>=70?"✅":"❌"}`);else lines.push("- Review pass rate: N/A (no reviews)");if(quality.testPassRate!==null)lines.push(`- Test pass rate: ${quality.testPassRate}% (${quality.testsPassed}/${quality.testsPassed+quality.testsFailed}) ${quality.testPassRate>=80?"✅":"❌"}`);else lines.push("- Test pass rate: N/A (no tests)");lines.push(`- Code churn: +${quality.additions} / -${quality.deletions} lines`)}lines.push("")}if(qualityMetrics?.hasEvidence)lines.push("### Quality Metrics"),lines.push(`- Complexity Delta: ${qualityMetrics.complexityDelta} (max: ${qualityMetrics.thresholds.maxComplexityDelta}) ${qualityMetrics.complexityDelta<=qualityMetrics.thresholds.maxComplexityDelta?"✅":"❌"}`),lines.push(`- Public API Delta: ${qualityMetrics.publicApiDelta} (max: ${qualityMetrics.thresholds.maxPublicApiDelta}) ${qualityMetrics.publicApiDelta<=qualityMetrics.thresholds.maxPublicApiDelta?"✅":"❌"}`),lines.push(`- Duplication Ratio: ${qualityMetrics.duplicationRatio}% (max: ${qualityMetrics.thresholds.maxDuplicationRatio}%) ${qualityMetrics.duplicationRatio<=qualityMetrics.thresholds.maxDuplicationRatio?"✅":"❌"}`),lines.push(`- Test-to-Code Ratio: ${qualityMetrics.testToCodeRatio}% (min: ${qualityMetrics.thresholds.minTestToCodeRatio}%) ${qualityMetrics.testToCodeRatio>=qualityMetrics.thresholds.minTestToCodeRatio?"✅":"❌"}`),lines.push("");if(costSummary)lines.push("### Cost Signals"),lines.push(`- Total tracked cost: $${costSummary.total_cost_usd.toFixed(6)} (${costSummary.delegations} delegations)`,`- Reported: $${costSummary.total_reported_usd.toFixed(6)}; estimated: $${costSummary.total_estimated_usd.toFixed(6)}; unavailable: ${costSummary.unavailable_delegations}`),lines.push("");if(ciGate){lines.push("### CI Gate",ciGate.passed?"✅ PASSED":"❌ FAILED");for(let c of ciGate.checks){let valueStr;if(c.name==="Complexity Delta"||c.name==="Public API Delta")valueStr=`${c.value}`;else if(c.name==="Total cost")valueStr=`$${c.value.toFixed(6)}`;else valueStr=`${c.value}%`;let thresholdStr=c.name==="Complexity Delta"||c.name==="Public API Delta"?`${c.threshold}`:c.name==="Total cost"?`$${c.threshold.toFixed(6)}`:`${c.threshold}%`;lines.push(`- ${c.name}: ${valueStr} ${c.operator} ${thresholdStr} ${c.passed?"✅":"❌"}`)}lines.push("")}let json2={mode,timestamp:new Date().toISOString(),agent_health:agentHealth.map((a)=>({agent:a.agent,tool_calls:a.toolCalls,hard_limit_hits:a.hardLimits,warnings:a.warnings})),tool_performance:toolPerf.map((t)=>({tool:t.tool,calls:t.calls,success_rate:t.successRate,avg_duration_ms:t.avg})),delegations:delegationCount};if(quality)json2.quality={review_pass_rate:quality.reviewPassRate,test_pass_rate:quality.testPassRate,total_reviews:quality.totalReviews,total_tests_passed:quality.testsPassed,total_tests_failed:quality.testsFailed,additions:quality.additions,deletions:quality.deletions};if(qualityMetrics)json2.quality_metrics={complexity_delta:qualityMetrics.complexityDelta,public_api_delta:qualityMetrics.publicApiDelta,duplication_ratio:qualityMetrics.duplicationRatio,test_to_code_ratio:qualityMetrics.testToCodeRatio,thresholds:qualityMetrics.thresholds,has_evidence:qualityMetrics.hasEvidence};if(costSummary)json2.costs={total_cost_usd:costSummary.total_cost_usd,total_reported_usd:costSummary.total_reported_usd,total_estimated_usd:costSummary.total_estimated_usd,total_input_tokens:costSummary.total_input_tokens,total_output_tokens:costSummary.total_output_tokens,total_reasoning_tokens:costSummary.total_reasoning_tokens,total_cache_tokens:costSummary.total_cache_tokens,delegations:costSummary.delegations,unavailable_delegations:costSummary.unavailable_delegations};if(ciGate)json2.ci_gate={passed:ciGate.passed,checks:ciGate.checks.map((c)=>({name:c.name,value:c.value,threshold:c.threshold,operator:c.operator,passed:c.passed}))};return lines.push("[BENCHMARK_JSON]",JSON.stringify(json2,null,2),"[/BENCHMARK_JSON]"),lines.join(`
651
651
  `)}function parseMaxCostUsd(args2){let index=args2.indexOf("--max-cost-usd");if(index===-1)return null;let raw=args2[index+1];if(!raw||raw.startsWith("--"))throw Error("Invalid --max-cost-usd value: expected a non-negative number.");let parsed=Number(raw);if(!Number.isFinite(parsed)||parsed<0)throw Error("Invalid --max-cost-usd value: expected a non-negative number.");return parsed}var CI;var init_benchmark=__esm(()=>{init_manager2();init_cost_accounting();init_state2();init_utils();CI={review_pass_rate:70,test_pass_rate:80,max_agent_error_rate:20,max_hard_limit_hits:1,max_complexity_delta:5,max_public_api_delta:10,max_duplication_ratio:5,min_test_to_code_ratio:30}});function sanitizeTopic(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim(),MAX_TOPIC_LEN=2000;if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}async function handleBrainstormCommand(_directory,args2){let description=sanitizeTopic(args2.join(" "));if(description)return`[MODE: BRAINSTORM] ${description}`;return"[MODE: BRAINSTORM] Please enter MODE: BRAINSTORM and begin the structured brainstorm workflow (CONTEXT SCAN → DIALOGUE → APPROACHES → DESIGN SECTIONS → SPEC WRITE + SELF-REVIEW → QA GATE SELECTION → TRANSITION)."}function $constructor2(name,initializer3,params){function init(inst,def){var _a2;Object.defineProperty(inst,"_zod",{value:inst._zod??{},enumerable:!1}),(_a2=inst._zod).traits??(_a2.traits=new Set),inst._zod.traits.add(name),initializer3(inst,def);for(let k in _.prototype)if(!(k in inst))Object.defineProperty(inst,k,{value:_.prototype[k].bind(inst)});inst._zod.constr=_,inst._zod.def=def}let Parent=params?.Parent??Object;class Definition extends Parent{}Object.defineProperty(Definition,"name",{value:name});function _(def){var _a2;let inst=params?.Parent?new Definition:this;init(inst,def),(_a2=inst._zod).deferred??(_a2.deferred=[]);for(let fn2 of inst._zod.deferred)fn2();return inst}return Object.defineProperty(_,"init",{value:init}),Object.defineProperty(_,Symbol.hasInstance,{value:(inst)=>{if(params?.Parent&&inst instanceof params.Parent)return!0;return inst?._zod?.traits?.has(name)}}),Object.defineProperty(_,"name",{value:name}),_}function config2(newConfig){if(newConfig)Object.assign(globalConfig2,newConfig);return globalConfig2}var NEVER2,$brand2,$ZodAsyncError2,$ZodEncodeError2,globalConfig2;var init_core4=__esm(()=>{NEVER2=Object.freeze({status:"aborted"});$brand2=Symbol("zod_brand");$ZodAsyncError2=class $ZodAsyncError2 extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};$ZodEncodeError2=class $ZodEncodeError2 extends Error{constructor(name){super(`Encountered unidirectional transform during encode: ${name}`);this.name="ZodEncodeError"}};globalConfig2={}});var exports_util2={};__export(exports_util2,{unwrapMessage:()=>unwrapMessage2,uint8ArrayToHex:()=>uint8ArrayToHex2,uint8ArrayToBase64url:()=>uint8ArrayToBase64url2,uint8ArrayToBase64:()=>uint8ArrayToBase642,stringifyPrimitive:()=>stringifyPrimitive2,shallowClone:()=>shallowClone2,safeExtend:()=>safeExtend2,required:()=>required2,randomString:()=>randomString2,propertyKeyTypes:()=>propertyKeyTypes2,promiseAllObject:()=>promiseAllObject2,primitiveTypes:()=>primitiveTypes2,prefixIssues:()=>prefixIssues2,pick:()=>pick2,partial:()=>partial2,optionalKeys:()=>optionalKeys2,omit:()=>omit2,objectClone:()=>objectClone2,numKeys:()=>numKeys2,nullish:()=>nullish3,normalizeParams:()=>normalizeParams2,mergeDefs:()=>mergeDefs2,merge:()=>merge2,jsonStringifyReplacer:()=>jsonStringifyReplacer2,joinValues:()=>joinValues2,issue:()=>issue2,isPlainObject:()=>isPlainObject4,isObject:()=>isObject2,hexToUint8Array:()=>hexToUint8Array2,getSizableOrigin:()=>getSizableOrigin2,getParsedType:()=>getParsedType2,getLengthableOrigin:()=>getLengthableOrigin2,getEnumValues:()=>getEnumValues2,getElementAtPath:()=>getElementAtPath2,floatSafeRemainder:()=>floatSafeRemainder2,finalizeIssue:()=>finalizeIssue2,extend:()=>extend2,escapeRegex:()=>escapeRegex3,esc:()=>esc2,defineLazy:()=>defineLazy2,createTransparentProxy:()=>createTransparentProxy2,cloneDef:()=>cloneDef2,clone:()=>clone2,cleanRegex:()=>cleanRegex2,cleanEnum:()=>cleanEnum2,captureStackTrace:()=>captureStackTrace2,cached:()=>cached2,base64urlToUint8Array:()=>base64urlToUint8Array2,base64ToUint8Array:()=>base64ToUint8Array2,assignProp:()=>assignProp2,assertNotEqual:()=>assertNotEqual2,assertNever:()=>assertNever2,assertIs:()=>assertIs2,assertEqual:()=>assertEqual2,assert:()=>assert2,allowsEval:()=>allowsEval2,aborted:()=>aborted2,NUMBER_FORMAT_RANGES:()=>NUMBER_FORMAT_RANGES2,Class:()=>Class2,BIGINT_FORMAT_RANGES:()=>BIGINT_FORMAT_RANGES2});function assertEqual2(val){return val}function assertNotEqual2(val){return val}function assertIs2(_arg){}function assertNever2(_x){throw Error()}function assert2(_){}function getEnumValues2(entries){let numericValues=Object.values(entries).filter((v)=>typeof v==="number");return Object.entries(entries).filter(([k,_])=>numericValues.indexOf(+k)===-1).map(([_,v])=>v)}function joinValues2(array2,separator="|"){return array2.map((val)=>stringifyPrimitive2(val)).join(separator)}function jsonStringifyReplacer2(_,value){if(typeof value==="bigint")return value.toString();return value}function cached2(getter){return{get value(){{let value=getter();return Object.defineProperty(this,"value",{value}),value}throw Error("cached value already set")}}}function nullish3(input){return input===null||input===void 0}function cleanRegex2(source){let start=source.startsWith("^")?1:0,end=source.endsWith("$")?source.length-1:source.length;return source.slice(start,end)}function floatSafeRemainder2(val,step){let valDecCount=(val.toString().split(".")[1]||"").length,stepString=step.toString(),stepDecCount=(stepString.split(".")[1]||"").length;if(stepDecCount===0&&/\d?e-\d?/.test(stepString)){let match=stepString.match(/\d?e-(\d?)/);if(match?.[1])stepDecCount=Number.parseInt(match[1])}let decCount=valDecCount>stepDecCount?valDecCount:stepDecCount,valInt=Number.parseInt(val.toFixed(decCount).replace(".","")),stepInt=Number.parseInt(step.toFixed(decCount).replace(".",""));return valInt%stepInt/10**decCount}function defineLazy2(object2,key,getter){let value=void 0;Object.defineProperty(object2,key,{get(){if(value===EVALUATING2)return;if(value===void 0)value=EVALUATING2,value=getter();return value},set(v){Object.defineProperty(object2,key,{value:v})},configurable:!0})}function objectClone2(obj){return Object.create(Object.getPrototypeOf(obj),Object.getOwnPropertyDescriptors(obj))}function assignProp2(target,prop,value){Object.defineProperty(target,prop,{value,writable:!0,enumerable:!0,configurable:!0})}function mergeDefs2(...defs){let mergedDescriptors={};for(let def of defs){let descriptors=Object.getOwnPropertyDescriptors(def);Object.assign(mergedDescriptors,descriptors)}return Object.defineProperties({},mergedDescriptors)}function cloneDef2(schema){return mergeDefs2(schema._zod.def)}function getElementAtPath2(obj,path51){if(!path51)return obj;return path51.reduce((acc,key)=>acc?.[key],obj)}function promiseAllObject2(promisesObj){let keys=Object.keys(promisesObj),promises4=keys.map((key)=>promisesObj[key]);return Promise.all(promises4).then((results)=>{let resolvedObj={};for(let i=0;i<keys.length;i++)resolvedObj[keys[i]]=results[i];return resolvedObj})}function randomString2(length=10){let str="";for(let i=0;i<length;i++)str+="abcdefghijklmnopqrstuvwxyz"[Math.floor(Math.random()*26)];return str}function esc2(str){return JSON.stringify(str)}function isObject2(data){return typeof data==="object"&&data!==null&&!Array.isArray(data)}function isPlainObject4(o){if(isObject2(o)===!1)return!1;let ctor=o.constructor;if(ctor===void 0)return!0;let prot=ctor.prototype;if(isObject2(prot)===!1)return!1;if(Object.prototype.hasOwnProperty.call(prot,"isPrototypeOf")===!1)return!1;return!0}function shallowClone2(o){if(isPlainObject4(o))return{...o};if(Array.isArray(o))return[...o];return o}function numKeys2(data){let keyCount=0;for(let key in data)if(Object.prototype.hasOwnProperty.call(data,key))keyCount++;return keyCount}function escapeRegex3(str){return str.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function clone2(inst,def,params){let cl=new inst._zod.constr(def??inst._zod.def);if(!def||params?.parent)cl._zod.parent=inst;return cl}function normalizeParams2(_params){let params=_params;if(!params)return{};if(typeof params==="string")return{error:()=>params};if(params?.message!==void 0){if(params?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");params.error=params.message}if(delete params.message,typeof params.error==="string")return{...params,error:()=>params.error};return params}function createTransparentProxy2(getter){let target;return new Proxy({},{get(_,prop,receiver){return target??(target=getter()),Reflect.get(target,prop,receiver)},set(_,prop,value,receiver){return target??(target=getter()),Reflect.set(target,prop,value,receiver)},has(_,prop){return target??(target=getter()),Reflect.has(target,prop)},deleteProperty(_,prop){return target??(target=getter()),Reflect.deleteProperty(target,prop)},ownKeys(_){return target??(target=getter()),Reflect.ownKeys(target)},getOwnPropertyDescriptor(_,prop){return target??(target=getter()),Reflect.getOwnPropertyDescriptor(target,prop)},defineProperty(_,prop,descriptor){return target??(target=getter()),Reflect.defineProperty(target,prop,descriptor)}})}function stringifyPrimitive2(value){if(typeof value==="bigint")return value.toString()+"n";if(typeof value==="string")return`"${value}"`;return`${value}`}function optionalKeys2(shape){return Object.keys(shape).filter((k)=>{return shape[k]._zod.optin==="optional"&&shape[k]._zod.optout==="optional"})}function pick2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;newShape[key]=currDef.shape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function omit2(schema,mask){let currDef=schema._zod.def,def=mergeDefs2(schema._zod.def,{get shape(){let newShape={...schema._zod.def.shape};for(let key in mask){if(!(key in currDef.shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;delete newShape[key]}return assignProp2(this,"shape",newShape),newShape},checks:[]});return clone2(schema,def)}function extend2(schema,shape){if(!isPlainObject4(shape))throw Error("Invalid input to extend: expected a plain object");let checks3=schema._zod.def.checks;if(checks3&&checks3.length>0)throw Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead.");let def=mergeDefs2(schema._zod.def,{get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:[]});return clone2(schema,def)}function safeExtend2(schema,shape){if(!isPlainObject4(shape))throw Error("Invalid input to safeExtend: expected a plain object");let def={...schema._zod.def,get shape(){let _shape={...schema._zod.def.shape,...shape};return assignProp2(this,"shape",_shape),_shape},checks:schema._zod.def.checks};return clone2(schema,def)}function merge2(a,b){let def=mergeDefs2(a._zod.def,{get shape(){let _shape={...a._zod.def.shape,...b._zod.def.shape};return assignProp2(this,"shape",_shape),_shape},get catchall(){return b._zod.def.catchall},checks:[]});return clone2(a,def)}function partial2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in oldShape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key]}else for(let key in oldShape)shape[key]=Class2?new Class2({type:"optional",innerType:oldShape[key]}):oldShape[key];return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function required2(Class2,schema,mask){let def=mergeDefs2(schema._zod.def,{get shape(){let oldShape=schema._zod.def.shape,shape={...oldShape};if(mask)for(let key in mask){if(!(key in shape))throw Error(`Unrecognized key: "${key}"`);if(!mask[key])continue;shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]})}else for(let key in oldShape)shape[key]=new Class2({type:"nonoptional",innerType:oldShape[key]});return assignProp2(this,"shape",shape),shape},checks:[]});return clone2(schema,def)}function aborted2(x,startIndex=0){if(x.aborted===!0)return!0;for(let i=startIndex;i<x.issues.length;i++)if(x.issues[i]?.continue!==!0)return!0;return!1}function prefixIssues2(path51,issues){return issues.map((iss)=>{var _a2;return(_a2=iss).path??(_a2.path=[]),iss.path.unshift(path51),iss})}function unwrapMessage2(message){return typeof message==="string"?message:message?.message}function finalizeIssue2(iss,ctx,config3){let full={...iss,path:iss.path??[]};if(!iss.message){let message=unwrapMessage2(iss.inst?._zod.def?.error?.(iss))??unwrapMessage2(ctx?.error?.(iss))??unwrapMessage2(config3.customError?.(iss))??unwrapMessage2(config3.localeError?.(iss))??"Invalid input";full.message=message}if(delete full.inst,delete full.continue,!ctx?.reportInput)delete full.input;return full}function getSizableOrigin2(input){if(input instanceof Set)return"set";if(input instanceof Map)return"map";if(input instanceof File)return"file";return"unknown"}function getLengthableOrigin2(input){if(Array.isArray(input))return"array";if(typeof input==="string")return"string";return"unknown"}function issue2(...args2){let[iss,input,inst]=args2;if(typeof iss==="string")return{message:iss,code:"custom",input,inst};return{...iss}}function cleanEnum2(obj){return Object.entries(obj).filter(([k,_])=>{return Number.isNaN(Number.parseInt(k,10))}).map((el)=>el[1])}function base64ToUint8Array2(base643){let binaryString=atob(base643),bytes=new Uint8Array(binaryString.length);for(let i=0;i<binaryString.length;i++)bytes[i]=binaryString.charCodeAt(i);return bytes}function uint8ArrayToBase642(bytes){let binaryString="";for(let i=0;i<bytes.length;i++)binaryString+=String.fromCharCode(bytes[i]);return btoa(binaryString)}function base64urlToUint8Array2(base64url3){let base643=base64url3.replace(/-/g,"+").replace(/_/g,"/"),padding="=".repeat((4-base643.length%4)%4);return base64ToUint8Array2(base643+padding)}function uint8ArrayToBase64url2(bytes){return uint8ArrayToBase642(bytes).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}function hexToUint8Array2(hex3){let cleanHex=hex3.replace(/^0x/,"");if(cleanHex.length%2!==0)throw Error("Invalid hex string length");let bytes=new Uint8Array(cleanHex.length/2);for(let i=0;i<cleanHex.length;i+=2)bytes[i/2]=Number.parseInt(cleanHex.slice(i,i+2),16);return bytes}function uint8ArrayToHex2(bytes){return Array.from(bytes).map((b)=>b.toString(16).padStart(2,"0")).join("")}class Class2{constructor(..._args){}}var EVALUATING2,captureStackTrace2,allowsEval2,getParsedType2=(data)=>{let t=typeof data;switch(t){case"undefined":return"undefined";case"string":return"string";case"number":return Number.isNaN(data)?"nan":"number";case"boolean":return"boolean";case"function":return"function";case"bigint":return"bigint";case"symbol":return"symbol";case"object":if(Array.isArray(data))return"array";if(data===null)return"null";if(data.then&&typeof data.then==="function"&&data.catch&&typeof data.catch==="function")return"promise";if(typeof Map<"u"&&data instanceof Map)return"map";if(typeof Set<"u"&&data instanceof Set)return"set";if(typeof Date<"u"&&data instanceof Date)return"date";if(typeof File<"u"&&data instanceof File)return"file";return"object";default:throw Error(`Unknown data type: ${t}`)}},propertyKeyTypes2,primitiveTypes2,NUMBER_FORMAT_RANGES2,BIGINT_FORMAT_RANGES2;var init_util2=__esm(()=>{EVALUATING2=Symbol("evaluating");captureStackTrace2="captureStackTrace"in Error?Error.captureStackTrace:(..._args)=>{};allowsEval2=cached2(()=>{if(typeof navigator<"u"&&navigator?.userAgent?.includes("Cloudflare"))return!1;try{return new Function(""),!0}catch(_){return!1}});propertyKeyTypes2=new Set(["string","number","symbol"]),primitiveTypes2=new Set(["string","number","bigint","boolean","symbol","undefined"]);NUMBER_FORMAT_RANGES2={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-340282346638528860000000000000000000000,340282346638528860000000000000000000000],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},BIGINT_FORMAT_RANGES2={int64:[BigInt("-9223372036854775808"),BigInt("9223372036854775807")],uint64:[BigInt(0),BigInt("18446744073709551615")]}});function flattenError2(error49,mapper=(issue3)=>issue3.message){let fieldErrors={},formErrors=[];for(let sub of error49.issues)if(sub.path.length>0)fieldErrors[sub.path[0]]=fieldErrors[sub.path[0]]||[],fieldErrors[sub.path[0]].push(mapper(sub));else formErrors.push(mapper(sub));return{formErrors,fieldErrors}}function formatError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},fieldErrors={_errors:[]},processError=(error50)=>{for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues}));else if(issue3.code==="invalid_key")processError({issues:issue3.issues});else if(issue3.code==="invalid_element")processError({issues:issue3.issues});else if(issue3.path.length===0)fieldErrors._errors.push(mapper(issue3));else{let curr=fieldErrors,i=0;while(i<issue3.path.length){let el=issue3.path[i];if(i!==issue3.path.length-1)curr[el]=curr[el]||{_errors:[]};else curr[el]=curr[el]||{_errors:[]},curr[el]._errors.push(mapper(issue3));curr=curr[el],i++}}};return processError(error49),fieldErrors}function treeifyError2(error49,_mapper){let mapper=_mapper||function(issue3){return issue3.message},result={errors:[]},processError=(error50,path51=[])=>{var _a2,_b;for(let issue3 of error50.issues)if(issue3.code==="invalid_union"&&issue3.errors.length)issue3.errors.map((issues)=>processError({issues},issue3.path));else if(issue3.code==="invalid_key")processError({issues:issue3.issues},issue3.path);else if(issue3.code==="invalid_element")processError({issues:issue3.issues},issue3.path);else{let fullpath=[...path51,...issue3.path];if(fullpath.length===0){result.errors.push(mapper(issue3));continue}let curr=result,i=0;while(i<fullpath.length){let el=fullpath[i],terminal=i===fullpath.length-1;if(typeof el==="string")curr.properties??(curr.properties={}),(_a2=curr.properties)[el]??(_a2[el]={errors:[]}),curr=curr.properties[el];else curr.items??(curr.items=[]),(_b=curr.items)[el]??(_b[el]={errors:[]}),curr=curr.items[el];if(terminal)curr.errors.push(mapper(issue3));i++}}};return processError(error49),result}function toDotPath2(_path){let segs=[],path51=_path.map((seg)=>typeof seg==="object"?seg.key:seg);for(let seg of path51)if(typeof seg==="number")segs.push(`[${seg}]`);else if(typeof seg==="symbol")segs.push(`[${JSON.stringify(String(seg))}]`);else if(/[^\w$]/.test(seg))segs.push(`[${JSON.stringify(seg)}]`);else{if(segs.length)segs.push(".");segs.push(seg)}return segs.join("")}function prettifyError2(error49){let lines=[],issues=[...error49.issues].sort((a,b)=>(a.path??[]).length-(b.path??[]).length);for(let issue3 of issues)if(lines.push(`✖ ${issue3.message}`),issue3.path?.length)lines.push(` → at ${toDotPath2(issue3.path)}`);return lines.join(`
652
652
  `)}var initializer3=(inst,def)=>{inst.name="$ZodError",Object.defineProperty(inst,"_zod",{value:inst._zod,enumerable:!1}),Object.defineProperty(inst,"issues",{value:def,enumerable:!1}),inst.message=JSON.stringify(def,jsonStringifyReplacer2,2),Object.defineProperty(inst,"toString",{value:()=>inst.message,enumerable:!1})},$ZodError2,$ZodRealError2;var init_errors5=__esm(()=>{init_core4();init_util2();$ZodError2=$constructor2("$ZodError",initializer3),$ZodRealError2=$constructor2("$ZodError",initializer3,{Parent:Error})});var _parse2=(_Err)=>(schema,value,_ctx,_params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!1}):{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;if(result.issues.length){let e=new(_params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,_params?.callee),e}return result.value},parse6,_parseAsync2=(_Err)=>async(schema,value,_ctx,params)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;if(result.issues.length){let e=new(params?.Err??_Err)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())));throw captureStackTrace2(e,params?.callee),e}return result.value},parseAsync3,_safeParse2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?{..._ctx,async:!1}:{async:!1},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)throw new $ZodAsyncError2;return result.issues.length?{success:!1,error:new(_Err??$ZodError2)(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParse3,_safeParseAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{async:!0}):{async:!0},result=schema._zod.run({value,issues:[]},ctx);if(result instanceof Promise)result=await result;return result.issues.length?{success:!1,error:new _Err(result.issues.map((iss)=>finalizeIssue2(iss,ctx,config2())))}:{success:!0,data:result.value}},safeParseAsync3,_encode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parse2(_Err)(schema,value,ctx)},encode3,_decode2=(_Err)=>(schema,value,_ctx)=>{return _parse2(_Err)(schema,value,_ctx)},decode3,_encodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _parseAsync2(_Err)(schema,value,ctx)},encodeAsync3,_decodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _parseAsync2(_Err)(schema,value,_ctx)},decodeAsync3,_safeEncode2=(_Err)=>(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParse2(_Err)(schema,value,ctx)},safeEncode3,_safeDecode2=(_Err)=>(schema,value,_ctx)=>{return _safeParse2(_Err)(schema,value,_ctx)},safeDecode3,_safeEncodeAsync2=(_Err)=>async(schema,value,_ctx)=>{let ctx=_ctx?Object.assign(_ctx,{direction:"backward"}):{direction:"backward"};return _safeParseAsync2(_Err)(schema,value,ctx)},safeEncodeAsync3,_safeDecodeAsync2=(_Err)=>async(schema,value,_ctx)=>{return _safeParseAsync2(_Err)(schema,value,_ctx)},safeDecodeAsync3;var init_parse3=__esm(()=>{init_core4();init_errors5();init_util2();parse6=_parse2($ZodRealError2),parseAsync3=_parseAsync2($ZodRealError2),safeParse3=_safeParse2($ZodRealError2),safeParseAsync3=_safeParseAsync2($ZodRealError2),encode3=_encode2($ZodRealError2),decode3=_decode2($ZodRealError2),encodeAsync3=_encodeAsync2($ZodRealError2),decodeAsync3=_decodeAsync2($ZodRealError2),safeEncode3=_safeEncode2($ZodRealError2),safeDecode3=_safeDecode2($ZodRealError2),safeEncodeAsync3=_safeEncodeAsync2($ZodRealError2),safeDecodeAsync3=_safeDecodeAsync2($ZodRealError2)});var exports_regexes2={};__export(exports_regexes2,{xid:()=>xid3,uuid7:()=>uuid72,uuid6:()=>uuid62,uuid4:()=>uuid42,uuid:()=>uuid3,uppercase:()=>uppercase2,unicodeEmail:()=>unicodeEmail2,undefined:()=>_undefined4,ulid:()=>ulid3,time:()=>time3,string:()=>string4,sha512_hex:()=>sha512_hex2,sha512_base64url:()=>sha512_base64url2,sha512_base64:()=>sha512_base642,sha384_hex:()=>sha384_hex2,sha384_base64url:()=>sha384_base64url2,sha384_base64:()=>sha384_base642,sha256_hex:()=>sha256_hex2,sha256_base64url:()=>sha256_base64url2,sha256_base64:()=>sha256_base642,sha1_hex:()=>sha1_hex2,sha1_base64url:()=>sha1_base64url2,sha1_base64:()=>sha1_base642,rfc5322Email:()=>rfc5322Email2,number:()=>number4,null:()=>_null4,nanoid:()=>nanoid3,md5_hex:()=>md5_hex2,md5_base64url:()=>md5_base64url2,md5_base64:()=>md5_base642,lowercase:()=>lowercase2,ksuid:()=>ksuid3,ipv6:()=>ipv63,ipv4:()=>ipv43,integer:()=>integer2,idnEmail:()=>idnEmail2,html5Email:()=>html5Email2,hostname:()=>hostname3,hex:()=>hex3,guid:()=>guid3,extendedDuration:()=>extendedDuration2,emoji:()=>emoji3,email:()=>email3,e164:()=>e1643,duration:()=>duration3,domain:()=>domain2,datetime:()=>datetime3,date:()=>date5,cuid2:()=>cuid23,cuid:()=>cuid5,cidrv6:()=>cidrv63,cidrv4:()=>cidrv43,browserEmail:()=>browserEmail2,boolean:()=>boolean4,bigint:()=>bigint4,base64url:()=>base64url3,base64:()=>base643});function emoji3(){return new RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")}function timeSource2(args2){return typeof args2.precision==="number"?args2.precision===-1?"(?:[01]\\d|2[0-3]):[0-5]\\d":args2.precision===0?"(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d":`(?:[01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d\\.\\d{${args2.precision}}`:"(?:[01]\\d|2[0-3]):[0-5]\\d(?::[0-5]\\d(?:\\.\\d+)?)?"}function time3(args2){return new RegExp(`^${timeSource2(args2)}$`)}function datetime3(args2){let time4=timeSource2({precision:args2.precision}),opts=["Z"];if(args2.local)opts.push("");if(args2.offset)opts.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");let timeRegex=`${time4}(?:${opts.join("|")})`;return new RegExp(`^${dateSource2}T(?:${timeRegex})$`)}function fixedBase642(bodyLength,padding){return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`)}function fixedBase64url2(length){return new RegExp(`^[A-Za-z0-9_-]{${length}}$`)}var cuid5,cuid23,ulid3,xid3,ksuid3,nanoid3,duration3,extendedDuration2,guid3,uuid3=(version2)=>{if(!version2)return/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/;return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version2}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`)},uuid42,uuid62,uuid72,email3,html5Email2,rfc5322Email2,unicodeEmail2,idnEmail2,browserEmail2,ipv43,ipv63,cidrv43,cidrv63,base643,base64url3,hostname3,domain2,e1643,dateSource2="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",date5,string4=(params)=>{let regex=params?`[\\s\\S]{${params?.minimum??0},${params?.maximum??""}}`:"[\\s\\S]*";return new RegExp(`^${regex}$`)},bigint4,integer2,number4,boolean4,_null4,_undefined4,lowercase2,uppercase2,hex3,md5_hex2,md5_base642,md5_base64url2,sha1_hex2,sha1_base642,sha1_base64url2,sha256_hex2,sha256_base642,sha256_base64url2,sha384_hex2,sha384_base642,sha384_base64url2,sha512_hex2,sha512_base642,sha512_base64url2;var init_regexes2=__esm(()=>{cuid5=/^[cC][^\s-]{8,}$/,cuid23=/^[0-9a-z]+$/,ulid3=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,xid3=/^[0-9a-vA-V]{20}$/,ksuid3=/^[A-Za-z0-9]{27}$/,nanoid3=/^[a-zA-Z0-9_-]{21}$/,duration3=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,extendedDuration2=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,guid3=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,uuid42=uuid3(4),uuid62=uuid3(6),uuid72=uuid3(7),email3=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,html5Email2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/,rfc5322Email2=/^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,unicodeEmail2=/^[^\s@"]{1,64}@[^\s@]{1,255}$/u,idnEmail2=unicodeEmail2,browserEmail2=/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;ipv43=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,cidrv43=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cidrv63=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base643=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,base64url3=/^[A-Za-z0-9_-]*$/,hostname3=/^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/,domain2=/^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/,e1643=/^\+(?:[0-9]){6,14}[0-9]$/,date5=new RegExp(`^${dateSource2}$`);bigint4=/^-?\d+n?$/,integer2=/^-?\d+$/,number4=/^-?\d+(?:\.\d+)?/,boolean4=/^(?:true|false)$/i,_null4=/^null$/i,_undefined4=/^undefined$/i,lowercase2=/^[^A-Z]*$/,uppercase2=/^[^a-z]*$/,hex3=/^[0-9a-fA-F]*$/;md5_hex2=/^[0-9a-fA-F]{32}$/,md5_base642=fixedBase642(22,"=="),md5_base64url2=fixedBase64url2(22),sha1_hex2=/^[0-9a-fA-F]{40}$/,sha1_base642=fixedBase642(27,"="),sha1_base64url2=fixedBase64url2(27),sha256_hex2=/^[0-9a-fA-F]{64}$/,sha256_base642=fixedBase642(43,"="),sha256_base64url2=fixedBase64url2(43),sha384_hex2=/^[0-9a-fA-F]{96}$/,sha384_base642=fixedBase642(64,""),sha384_base64url2=fixedBase64url2(64),sha512_hex2=/^[0-9a-fA-F]{128}$/,sha512_base642=fixedBase642(86,"=="),sha512_base64url2=fixedBase64url2(86)});function handleCheckPropertyResult2(result,payload,property){if(result.issues.length)payload.issues.push(...prefixIssues2(property,result.issues))}var $ZodCheck2,numericOriginMap2,$ZodCheckLessThan2,$ZodCheckGreaterThan2,$ZodCheckMultipleOf2,$ZodCheckNumberFormat2,$ZodCheckBigIntFormat2,$ZodCheckMaxSize2,$ZodCheckMinSize2,$ZodCheckSizeEquals2,$ZodCheckMaxLength2,$ZodCheckMinLength2,$ZodCheckLengthEquals2,$ZodCheckStringFormat2,$ZodCheckRegex2,$ZodCheckLowerCase2,$ZodCheckUpperCase2,$ZodCheckIncludes2,$ZodCheckStartsWith2,$ZodCheckEndsWith2,$ZodCheckProperty2,$ZodCheckMimeType2,$ZodCheckOverwrite2;var init_checks3=__esm(()=>{init_core4();init_regexes2();init_util2();$ZodCheck2=$constructor2("$ZodCheck",(inst,def)=>{var _a2;inst._zod??(inst._zod={}),inst._zod.def=def,(_a2=inst._zod).onattach??(_a2.onattach=[])}),numericOriginMap2={number:"number",bigint:"bigint",object:"date"},$ZodCheckLessThan2=$constructor2("$ZodCheckLessThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.maximum:bag.exclusiveMaximum)??Number.POSITIVE_INFINITY;if(def.value<curr)if(def.inclusive)bag.maximum=def.value;else bag.exclusiveMaximum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value<=def.value:payload.value<def.value)return;payload.issues.push({origin,code:"too_big",maximum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckGreaterThan2=$constructor2("$ZodCheckGreaterThan",(inst,def)=>{$ZodCheck2.init(inst,def);let origin=numericOriginMap2[typeof def.value];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag,curr=(def.inclusive?bag.minimum:bag.exclusiveMinimum)??Number.NEGATIVE_INFINITY;if(def.value>curr)if(def.inclusive)bag.minimum=def.value;else bag.exclusiveMinimum=def.value}),inst._zod.check=(payload)=>{if(def.inclusive?payload.value>=def.value:payload.value>def.value)return;payload.issues.push({origin,code:"too_small",minimum:def.value,input:payload.value,inclusive:def.inclusive,inst,continue:!def.abort})}}),$ZodCheckMultipleOf2=$constructor2("$ZodCheckMultipleOf",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{var _a2;(_a2=inst2._zod.bag).multipleOf??(_a2.multipleOf=def.value)}),inst._zod.check=(payload)=>{if(typeof payload.value!==typeof def.value)throw Error("Cannot mix number and bigint in multiple_of check.");if(typeof payload.value==="bigint"?payload.value%def.value===BigInt(0):floatSafeRemainder2(payload.value,def.value)===0)return;payload.issues.push({origin:typeof payload.value,code:"not_multiple_of",divisor:def.value,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckNumberFormat2=$constructor2("$ZodCheckNumberFormat",(inst,def)=>{$ZodCheck2.init(inst,def),def.format=def.format||"float64";let isInt=def.format?.includes("int"),origin=isInt?"int":"number",[minimum,maximum]=NUMBER_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum,isInt)bag.pattern=integer2}),inst._zod.check=(payload)=>{let input=payload.value;if(isInt){if(!Number.isInteger(input)){payload.issues.push({expected:origin,format:def.format,code:"invalid_type",continue:!1,input,inst});return}if(!Number.isSafeInteger(input)){if(input>0)payload.issues.push({input,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});else payload.issues.push({input,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst,origin,continue:!def.abort});return}}if(input<minimum)payload.issues.push({origin:"number",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"number",input,code:"too_big",maximum,inst})}}),$ZodCheckBigIntFormat2=$constructor2("$ZodCheckBigIntFormat",(inst,def)=>{$ZodCheck2.init(inst,def);let[minimum,maximum]=BIGINT_FORMAT_RANGES2[def.format];inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.format=def.format,bag.minimum=minimum,bag.maximum=maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input<minimum)payload.issues.push({origin:"bigint",input,code:"too_small",minimum,inclusive:!0,inst,continue:!def.abort});if(input>maximum)payload.issues.push({origin:"bigint",input,code:"too_big",maximum,inst})}}),$ZodCheckMaxSize2=$constructor2("$ZodCheckMaxSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size<=def.maximum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinSize2=$constructor2("$ZodCheckMinSize",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.size>=def.minimum)return;payload.issues.push({origin:getSizableOrigin2(input),code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckSizeEquals2=$constructor2("$ZodCheckSizeEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.size!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.size,bag.maximum=def.size,bag.size=def.size}),inst._zod.check=(payload)=>{let input=payload.value,size=input.size;if(size===def.size)return;let tooBig=size>def.size;payload.issues.push({origin:getSizableOrigin2(input),...tooBig?{code:"too_big",maximum:def.size}:{code:"too_small",minimum:def.size},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckMaxLength2=$constructor2("$ZodCheckMaxLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.maximum??Number.POSITIVE_INFINITY;if(def.maximum<curr)inst2._zod.bag.maximum=def.maximum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length<=def.maximum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_big",maximum:def.maximum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckMinLength2=$constructor2("$ZodCheckMinLength",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let curr=inst2._zod.bag.minimum??Number.NEGATIVE_INFINITY;if(def.minimum>curr)inst2._zod.bag.minimum=def.minimum}),inst._zod.check=(payload)=>{let input=payload.value;if(input.length>=def.minimum)return;let origin=getLengthableOrigin2(input);payload.issues.push({origin,code:"too_small",minimum:def.minimum,inclusive:!0,input,inst,continue:!def.abort})}}),$ZodCheckLengthEquals2=$constructor2("$ZodCheckLengthEquals",(inst,def)=>{var _a2;$ZodCheck2.init(inst,def),(_a2=inst._zod.def).when??(_a2.when=(payload)=>{let val=payload.value;return!nullish3(val)&&val.length!==void 0}),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.minimum=def.length,bag.maximum=def.length,bag.length=def.length}),inst._zod.check=(payload)=>{let input=payload.value,length=input.length;if(length===def.length)return;let origin=getLengthableOrigin2(input),tooBig=length>def.length;payload.issues.push({origin,...tooBig?{code:"too_big",maximum:def.length}:{code:"too_small",minimum:def.length},inclusive:!0,exact:!0,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStringFormat2=$constructor2("$ZodCheckStringFormat",(inst,def)=>{var _a2,_b;if($ZodCheck2.init(inst,def),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;if(bag.format=def.format,def.pattern)bag.patterns??(bag.patterns=new Set),bag.patterns.add(def.pattern)}),def.pattern)(_a2=inst._zod).check??(_a2.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:def.format,input:payload.value,...def.pattern?{pattern:def.pattern.toString()}:{},inst,continue:!def.abort})});else(_b=inst._zod).check??(_b.check=()=>{})}),$ZodCheckRegex2=$constructor2("$ZodCheckRegex",(inst,def)=>{$ZodCheckStringFormat2.init(inst,def),inst._zod.check=(payload)=>{if(def.pattern.lastIndex=0,def.pattern.test(payload.value))return;payload.issues.push({origin:"string",code:"invalid_format",format:"regex",input:payload.value,pattern:def.pattern.toString(),inst,continue:!def.abort})}}),$ZodCheckLowerCase2=$constructor2("$ZodCheckLowerCase",(inst,def)=>{def.pattern??(def.pattern=lowercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckUpperCase2=$constructor2("$ZodCheckUpperCase",(inst,def)=>{def.pattern??(def.pattern=uppercase2),$ZodCheckStringFormat2.init(inst,def)}),$ZodCheckIncludes2=$constructor2("$ZodCheckIncludes",(inst,def)=>{$ZodCheck2.init(inst,def);let escapedRegex=escapeRegex3(def.includes),pattern=new RegExp(typeof def.position==="number"?`^.{${def.position}}${escapedRegex}`:escapedRegex);def.pattern=pattern,inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.includes(def.includes,def.position))return;payload.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:def.includes,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckStartsWith2=$constructor2("$ZodCheckStartsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`^${escapeRegex3(def.prefix)}.*`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.startsWith(def.prefix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:def.prefix,input:payload.value,inst,continue:!def.abort})}}),$ZodCheckEndsWith2=$constructor2("$ZodCheckEndsWith",(inst,def)=>{$ZodCheck2.init(inst,def);let pattern=new RegExp(`.*${escapeRegex3(def.suffix)}$`);def.pattern??(def.pattern=pattern),inst._zod.onattach.push((inst2)=>{let bag=inst2._zod.bag;bag.patterns??(bag.patterns=new Set),bag.patterns.add(pattern)}),inst._zod.check=(payload)=>{if(payload.value.endsWith(def.suffix))return;payload.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:def.suffix,input:payload.value,inst,continue:!def.abort})}});$ZodCheckProperty2=$constructor2("$ZodCheckProperty",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{let result=def.schema._zod.run({value:payload.value[def.property],issues:[]},{});if(result instanceof Promise)return result.then((result2)=>handleCheckPropertyResult2(result2,payload,def.property));handleCheckPropertyResult2(result,payload,def.property);return}}),$ZodCheckMimeType2=$constructor2("$ZodCheckMimeType",(inst,def)=>{$ZodCheck2.init(inst,def);let mimeSet=new Set(def.mime);inst._zod.onattach.push((inst2)=>{inst2._zod.bag.mime=def.mime}),inst._zod.check=(payload)=>{if(mimeSet.has(payload.value.type))return;payload.issues.push({code:"invalid_value",values:def.mime,input:payload.value.type,inst,continue:!def.abort})}}),$ZodCheckOverwrite2=$constructor2("$ZodCheckOverwrite",(inst,def)=>{$ZodCheck2.init(inst,def),inst._zod.check=(payload)=>{payload.value=def.tx(payload.value)}})});class Doc2{constructor(args2=[]){if(this.content=[],this.indent=0,this)this.args=args2}indented(fn2){this.indent+=1,fn2(this),this.indent-=1}write(arg){if(typeof arg==="function"){arg(this,{execution:"sync"}),arg(this,{execution:"async"});return}let lines=arg.split(`
653
653
  `).filter((x)=>x),minIndent=Math.min(...lines.map((x)=>x.length-x.trimStart().length)),dedented=lines.map((x)=>x.slice(minIndent)).map((x)=>" ".repeat(this.indent*2)+x);for(let line of dedented)this.content.push(line)}compile(){let F=Function,args2=this?.args,lines=[...(this?.content??[""]).map((x)=>` ${x}`)];return new F(...args2,lines.join(`
@@ -1398,7 +1398,7 @@ Flags:
1398
1398
  `)}catch(err){return["Skill consolidation encountered an error.","",`Error: ${err instanceof Error?err.message:String(err)}`].join(`
1399
1399
  `)}}var init_consolidate=__esm(()=>{init_config();init_schema();init_skill_consolidation()});async function handleCostsCommand(directory,args2){let summary=summarizeTelemetryCosts(directory);if(args2.includes("--json"))return["[COSTS_JSON]",JSON.stringify(summary,null,2),"[/COSTS_JSON]"].join(`
1400
1400
  `);return renderCostSummary(summary)}function renderCostSummary(summary){let lines=["## Swarm Costs","",`Total tracked cost: ${formatUsd(summary.total_cost_usd)}`,`Delegations: ${summary.delegations}`,`Tokens: input ${summary.total_input_tokens.toLocaleString()}, output ${summary.total_output_tokens.toLocaleString()}, reasoning ${summary.total_reasoning_tokens.toLocaleString()}, cache ${summary.total_cache_tokens.toLocaleString()}`,`Cost source: reported ${formatUsd(summary.total_reported_usd)}, estimated ${formatUsd(summary.total_estimated_usd)}, unavailable ${summary.unavailable_delegations}`,"","### By Agent"];return appendCostRows(lines,"Agent",summary.by_agent,"No delegation cost telemetry recorded."),lines.push("","### By Task"),appendCostRows(lines,"Task",summary.by_task,"No task cost telemetry recorded."),lines.push("","### By Gate"),appendCostRows(lines,"Gate",summary.by_gate,"No gate cost telemetry recorded."),lines.push("","### By Retry Loop"),appendCostRows(lines,"Retry",summary.by_retry,"No retry-loop cost telemetry recorded."),lines.join(`
1401
- `)}function appendCostRows(lines,label,rows,emptyMessage){if(rows.length===0){lines.push(emptyMessage);return}lines.push(`| ${label} | Delegations | Cost | Input | Output | Reasoning | Cache | Unavailable |`,"|------|-------------|------|-------|--------|-----------|-------|-------------|");for(let row of rows)lines.push(`| ${row.name} | ${row.delegations} | ${formatUsd(row.cost_usd)} | ${row.input_tokens.toLocaleString()} | ${row.output_tokens.toLocaleString()} | ${row.reasoning_tokens.toLocaleString()} | ${row.cache_tokens.toLocaleString()} | ${row.unavailable_delegations} |`)}function formatUsd(value){return`$${value.toFixed(6)}`}var init_costs=__esm(()=>{init_cost_accounting()});function sanitizeQuestion(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}function sanitizePresetName(raw){let trimmed=raw.trim();if(!trimmed)return null;if(trimmed.length>64)return null;if(!/^[A-Za-z0-9_-]+$/.test(trimmed))return null;return trimmed}function parseArgs2(args2){let out={specReview:!1,rest:[]};for(let i=0;i<args2.length;i++){let token=args2[i];if(token==="--spec-review"){out.specReview=!0;continue}if(token==="--preset"){let next=args2[i+1];if(next!==void 0){let sanitized=sanitizePresetName(next);if(sanitized)out.preset=sanitized;i++}continue}out.rest.push(token)}return out}async function handleCouncilCommand(_directory,args2){let parsed=parseArgs2(args2),question=sanitizeQuestion(parsed.rest.join(" "));if(!question)return USAGE;let tokens=["MODE: COUNCIL"];if(parsed.preset)tokens.push(`preset=${parsed.preset}`);if(parsed.specReview)tokens.push("spec_review");return`[${tokens.join(" ")}] ${question}`}var USAGE;var init_council=__esm(()=>{USAGE=["Usage: /swarm council <question> [--preset <name>] [--spec-review]",""," question The question to put to the council"," --preset <name> Use a named member preset from council.general.presets"," --spec-review Use spec_review mode (single advisory pass on a draft spec)","","Requires council.general.enabled: true and a configured search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides."].join(`
1401
+ `)}function appendCostRows(lines,label,rows,emptyMessage){if(rows.length===0){lines.push(emptyMessage);return}lines.push(`| ${label} | Delegations | Cost | Input | Output | Reasoning | Cache | Unavailable |`,"|------|-------------|------|-------|--------|-----------|-------|-------------|");for(let row of rows)lines.push(`| ${row.name} | ${row.delegations} | ${formatUsd(row.cost_usd)} | ${row.input_tokens.toLocaleString()} | ${row.output_tokens.toLocaleString()} | ${row.reasoning_tokens.toLocaleString()} | ${row.cache_tokens.toLocaleString()} | ${row.unavailable_delegations} |`)}function formatUsd(value){return`$${value.toFixed(6)}`}var init_costs=__esm(()=>{init_cost_accounting()});function sanitizeQuestion(raw){let normalized=raw.replace(/\s+/g," ").trim().replace(/\[\s*MODE\s*:[^\]]*\]/gi,"").replace(/\s+/g," ").trim();if(normalized.length<=2000)return normalized;return`${normalized.slice(0,2000)}…`}function sanitizePresetName(raw){let trimmed=raw.trim();if(!trimmed)return null;if(trimmed.length>64)return null;if(!/^[A-Za-z0-9_-]+$/.test(trimmed))return null;return trimmed}function parseArgs2(args2){let out={specReview:!1,rest:[]};for(let i=0;i<args2.length;i++){let token=args2[i];if(token==="--spec-review"){out.specReview=!0;continue}if(token==="--preset"){let next=args2[i+1];if(next!==void 0){let sanitized=sanitizePresetName(next);if(sanitized)out.preset=sanitized;i++}continue}out.rest.push(token)}return out}async function handleCouncilCommand(_directory,args2){let parsed=parseArgs2(args2),question=sanitizeQuestion(parsed.rest.join(" "));if(!question)return USAGE;let tokens=["MODE: COUNCIL"];if(parsed.preset)tokens.push(`preset=${parsed.preset}`);if(parsed.specReview)tokens.push("spec_review");return`[${tokens.join(" ")}] ${question}`}var USAGE;var init_council=__esm(()=>{USAGE=["Usage: /swarm council <question> [--spec-review]",""," question The question to put to the council"," --spec-review Use spec_review mode (single advisory pass on a draft spec)","","Requires council.general.enabled: true and a configured search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides."].join(`
1402
1402
  `)});import*as child_process5 from"node:child_process";import{randomUUID as randomUUID8}from"node:crypto";import{readdir as readdir5,readFile as readFile21,stat as stat10}from"node:fs/promises";import*as path79 from"node:path";import{promisify}from"node:util";function getExecFileAsync(){return promisify(child_process5.execFile)}async function parseGitLog(directory,maxCommits){let commitMap=new Map;try{let{stdout}=await getExecFileAsync()("git",["log","--name-only","--pretty=format:COMMIT:%H","--no-merges",`-n${maxCommits}`],{cwd:directory,timeout:1e4}),currentCommit=null;for(let line of stdout.split(`
1403
1403
  `))if(line.startsWith("COMMIT:")){if(currentCommit=line.slice(7),currentCommit&&!commitMap.has(currentCommit))commitMap.set(currentCommit,new Set)}else if(currentCommit&&line.trim()){let filePath=line.trim();if(filePath.startsWith(".swarm/")||filePath.startsWith("node_modules/")||filePath==="")continue;commitMap.get(currentCommit).add(filePath)}}catch{return new Map}return commitMap}function buildCoChangeMatrix(commitMap,maxFilesPerCommit=500){let matrix=new Map,fileCommitCount=new Map;for(let files of commitMap.values()){for(let file3 of files)fileCommitCount.set(file3,(fileCommitCount.get(file3)||0)+1);if(files.size>maxFilesPerCommit)continue;let fileArray=Array.from(files).sort();for(let i=0;i<fileArray.length;i++)for(let j=i+1;j<fileArray.length;j++){let fileA=fileArray[i],fileB=fileArray[j],[key,a,b]=fileA<fileB?[`${fileA}::${fileB}`,fileA,fileB]:[`${fileB}::${fileA}`,fileB,fileA],existing=matrix.get(key);if(existing)existing.coChangeCount++;else matrix.set(key,{fileA:a,fileB:b,coChangeCount:1,npmi:0,lift:0,hasStaticEdge:!1,totalCommits:0,commitsA:0,commitsB:0})}}let totalCommits=commitMap.size;for(let entry of matrix.values()){if(entry.coChangeCount<3)continue;let pAB=entry.coChangeCount/totalCommits,pA=(fileCommitCount.get(entry.fileA)||0)/totalCommits,pB=(fileCommitCount.get(entry.fileB)||0)/totalCommits;if(entry.commitsA=fileCommitCount.get(entry.fileA)||0,entry.commitsB=fileCommitCount.get(entry.fileB)||0,entry.totalCommits=totalCommits,pA>0&&pB>0)entry.lift=pAB/(pA*pB);if(pAB>0){let logPAB=Math.log(pAB),negLogPAB=-logPAB;if(negLogPAB>0){let numerator=logPAB-Math.log(pA*pB);entry.npmi=numerator/negLogPAB,entry.npmi=Math.max(-1,Math.min(1,entry.npmi))}else entry.npmi=1}}return matrix}async function scanSourceFiles(dir){let results=[],skipDirs=new Set(["node_modules",".swarm","dist","build"]);try{let entries=await readdir5(dir,{withFileTypes:!0});for(let entry of entries){let fullPath=path79.join(dir,entry.name);if(entry.isDirectory()){if(skipDirs.has(entry.name))continue;let subFiles=await scanSourceFiles(fullPath);results.push(...subFiles)}else if(entry.isFile()){let ext=path79.extname(entry.name);if([".ts",".tsx",".js",".jsx",".mjs"].includes(ext))results.push(fullPath)}}}catch{}return results}async function getStaticEdges(directory){let edges=new Set,sourceFiles=await scanSourceFiles(directory);for(let sourceFile of sourceFiles)try{let content=await readFile21(sourceFile,"utf-8"),importRegex=/(?:import|require)\s*(?:\(?\s*['"`]|.*?from\s+['"`])([^'"`]+)['"`]/g;for(let match=importRegex.exec(content);match!==null;match=importRegex.exec(content)){let importPath=match[1].trim();if(!importPath.startsWith("."))continue;try{let sourceDir=path79.dirname(sourceFile),resolvedPath=path79.resolve(sourceDir,importPath),extensions=["",".ts",".tsx",".js",".jsx",".mjs","/index.ts","/index.js"],targetFile=null;for(let ext of extensions){let testPath=resolvedPath+ext;try{if((await stat10(testPath)).isFile()){targetFile=testPath;break}}catch{}}if(!targetFile)continue;let relSource=path79.relative(directory,sourceFile).replace(/\\/g,"/"),relTarget=path79.relative(directory,targetFile).replace(/\\/g,"/"),[key]=relSource<relTarget?[`${relSource}::${relTarget}`,relSource,relTarget]:[`${relTarget}::${relSource}`,relTarget,relSource];edges.add(key)}catch{}}}catch{}return edges}function isTestImplementationPair(fileA,fileB){let testPatterns=[".test.ts",".test.js",".spec.ts",".spec.js"],getBaseName=(filePath)=>{let base=path79.basename(filePath);for(let pattern of testPatterns)if(base.endsWith(pattern))return base.slice(0,-pattern.length);return base.replace(/\.(ts|js|tsx|jsx|mjs)$/,"")},baseA=getBaseName(fileA),baseB=getBaseName(fileB);return baseA===baseB&&baseA!==path79.basename(fileA)&&baseA!==path79.basename(fileB)}function hasSharedPrefix(fileA,fileB){let dirA=path79.dirname(fileA),dirB=path79.dirname(fileB);if(dirA!==dirB)return!1;let baseA=path79.basename(fileA).replace(/\.(ts|js|tsx|jsx|mjs)$/,""),baseB=path79.basename(fileB).replace(/\.(ts|js|tsx|jsx|mjs)$/,"");if(baseA.startsWith(baseB)||baseB.startsWith(baseA))return!0;let splitA=baseA.split(/-|_/),splitB=baseB.split(/-|_/);if(splitA.length>0&&splitB.length>0&&splitA[0]===splitB[0])return!0;return!1}async function detectDarkMatter(directory,options){let minCommits=options?.minCommits??20,minCoChanges=options?.minCoChanges??3,npmiThreshold=options?.npmiThreshold??0.5,maxCommitsToAnalyze=options?.maxCommitsToAnalyze??500,maxFilesPerCommit=options?.maxFilesPerCommit??500;try{let{stdout}=await getExecFileAsync()("git",["rev-list","--count","HEAD"],{cwd:directory,timeout:1e4}),totalCommitCount=parseInt(stdout.trim(),10);if(Number.isNaN(totalCommitCount)||totalCommitCount<minCommits)return[]}catch{return[]}let commitMap=await _internals47.parseGitLog(directory,maxCommitsToAnalyze),matrix=_internals47.buildCoChangeMatrix(commitMap,maxFilesPerCommit),staticEdges=await _internals47.getStaticEdges(directory),results=[];for(let entry of matrix.values()){let key=`${entry.fileA}::${entry.fileB}`;if(entry.hasStaticEdge=staticEdges.has(key),entry.coChangeCount<minCoChanges)continue;if(entry.npmi<npmiThreshold)continue;if(entry.hasStaticEdge)continue;if(isTestImplementationPair(entry.fileA,entry.fileB))continue;if(hasSharedPrefix(entry.fileA,entry.fileB))continue;results.push(entry)}return results.sort((a,b)=>b.npmi-a.npmi),results.slice(0,20)}function darkMatterToKnowledgeEntries(pairs,projectName){let entries=[],now=new Date().toISOString();for(let pair of pairs.slice(0,10)){let baseA=path79.basename(pair.fileA),baseB=path79.basename(pair.fileB),lesson=`Files ${pair.fileA} and ${pair.fileB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;if(lesson.length>280)lesson=`Files ${baseA} and ${baseB} co-change with NPMI=${pair.npmi.toFixed(3)} but have no import relationship. This hidden coupling suggests a shared architectural concern — changes to one likely require changes to the other.`;if(lesson.length>280)lesson=`Files ${baseA} and ${baseB} co-change frequently (NPMI=${pair.npmi.toFixed(3)}) without import relationship. This hidden coupling suggests a shared architectural concern.`;if(lesson.length>280)lesson=`Hidden coupling: ${baseA.slice(0,50)}... ↔ ${baseB.slice(0,50)}... (NPMI=${pair.npmi.toFixed(3)})`;let confidence=Math.min(0.3+0.2*Math.min(pair.coChangeCount/10,1),0.5);entries.push({id:randomUUID8(),tier:"swarm",lesson,category:"architecture",tags:["hidden-coupling","co-change","dark-matter"],scope:"global",confidence,status:"candidate",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:now,updated_at:now,auto_generated:!0,project_name:projectName,applies_to_agents:["coder","reviewer"],required_actions:[`when modifying ${baseA}, check whether ${baseB} needs a matching change (and vice versa)`.slice(0,200)],verification_checks:[`coupled file ${baseB} was considered when ${baseA} changed`.slice(0,200)],triggers:[baseA,baseB].map((t)=>t.slice(0,80))})}return entries}function formatDarkMatterOutput(pairs){if(pairs.length===0)return`## Dark Matter: Hidden Couplings
1404
1404
 
@@ -1570,7 +1570,7 @@ Usage:
1570
1570
  `)}var _internals56;var init_evidence_service=__esm(()=>{init_manager2();_internals56={loadEvidence,listEvidenceTaskIds}});var init_evidence=__esm(()=>{init_evidence_service()});async function getExportData(directory){let planStructured=await loadPlanJsonOnly(directory),planContent=await readSwarmFileAsync(directory,"plan.md"),contextContent=await readSwarmFileAsync(directory,"context.md");return{version:"4.5.0",exported:new Date().toISOString(),plan:planStructured||planContent,context:contextContent,execution_profile:planStructured?.execution_profile??null}}function formatExportMarkdown(exportData){return["## Swarm Export","","```json",JSON.stringify(exportData,null,2),"```"].join(`
1571
1571
  `)}async function handleExportCommand(directory,_args){let exportData=await getExportData(directory);return formatExportMarkdown(exportData)}var init_export_service=__esm(()=>{init_utils2();init_manager()});var init_export=__esm(()=>{init_export_service()});import*as fs41 from"node:fs";import*as path89 from"node:path";function nowISO3(){return new Date().toISOString()}function ensureSwarmDir4(directory){let swarmDir=path89.resolve(directory,".swarm");if(!fs41.existsSync(swarmDir))fs41.mkdirSync(swarmDir,{recursive:!0});return swarmDir}function emptyCounters(){return{architectTurns:0,toolCalls:0,coderDelegations:0,reviewerRejections:0,testFailures:0,oversightChecks:0,consecutiveNoProgressTurns:0,consecutiveOversightFailures:0}}function sanitizeRunState(raw){if(!raw||typeof raw!=="object"||Array.isArray(raw))return null;let r=raw;if(typeof r.sessionID!=="string"||!r.sessionID)return null;let mode=VALID_RUN_MODES.has(r.mode)?r.mode:"supervised",status=VALID_RUN_STATUSES.has(r.status)?r.status:"idle";return{...raw,mode,status}}function sanitizeSessions(raw){let result={};for(let[id,session]of Object.entries(raw)){let sanitized=sanitizeRunState(session);if(sanitized)result[id]=sanitized}return result}function emptyState(sessionID,mode="supervised"){let now=nowISO3();return{status:"idle",sessionID,mode,startedAt:now,updatedAt:now,denialCounters:{consecutive:0,total:0},denialHistory:[],counters:emptyCounters()}}function withStateLock(directory,fn2){let release;try{let lockTarget=validateSwarmPath(directory,STATE_FILE3);if(!fs41.existsSync(lockTarget)){ensureSwarmDir4(directory);let seed={version:2,updatedAt:nowISO3(),oversightSequence:0,sessions:{}};fs41.writeFileSync(lockTarget,`${JSON.stringify(seed,null,2)}
1572
1572
  `,"utf-8")}release=lockfile8.lockSync(lockTarget,{retries:{retries:5,minTimeout:5,maxTimeout:50},stale:5000})}catch(error93){warn(`[full-auto/state] cross-process lock unavailable; proceeding unlocked: ${error93 instanceof Error?error93.message:String(error93)}`)}try{return fn2()}finally{if(release)try{release()}catch(releaseError){warn(`[full-auto/state] lock release failed: ${releaseError instanceof Error?releaseError.message:String(releaseError)}`)}}}function emptyPersisted2(){return{version:2,updatedAt:nowISO3(),oversightSequence:0,sessions:{}}}function markStateUnreadable2(reason){stateUnreadable=!0,stateUnreadableReason=reason,error48(`[full-auto/state] state file unreadable: ${reason} — failing closed`)}function clearStateUnreadable(){stateUnreadable=!1,stateUnreadableReason=""}function isFullAutoStateUnreadable(){return{unreadable:stateUnreadable,reason:stateUnreadableReason}}function readPersisted2(directory){try{let filePath=validateSwarmPath(directory,STATE_FILE3),stats2;try{stats2=fs41.statSync(filePath)}catch{return clearStateUnreadable(),readCache.delete(filePath),emptyPersisted2()}let cached3=readCache.get(filePath);if(cached3&&cached3.mtimeMs===stats2.mtimeMs&&cached3.size===stats2.size)return clearStateUnreadable(),structuredClone(cached3.state);let raw=fs41.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(!parsed||typeof parsed!=="object"||Array.isArray(parsed)||parsed.version!==2||!parsed.sessions||typeof parsed.sessions!=="object"||Array.isArray(parsed.sessions))return markStateUnreadable2(`malformed shape (version=${parsed?.version}, sessions type=${Array.isArray(parsed?.sessions)?"array":typeof parsed?.sessions})`),readCache.delete(filePath),emptyPersisted2();clearStateUnreadable();let state={version:2,updatedAt:parsed.updatedAt??nowISO3(),oversightSequence:typeof parsed.oversightSequence==="number"?parsed.oversightSequence:0,sessions:sanitizeSessions(parsed.sessions)};return readCache.set(filePath,{mtimeMs:stats2.mtimeMs,size:stats2.size,state:structuredClone(state)}),state}catch(error93){let reason=error93 instanceof Error?error93.message:String(error93);error48(`[full-auto/state] Failed to read ${STATE_FILE3}: ${reason} — attempting .bak recovery`);try{let bakPath=validateSwarmPath(directory,`${STATE_FILE3}.bak`);if(fs41.existsSync(bakPath)){let raw=fs41.readFileSync(bakPath,"utf-8"),parsed=JSON.parse(raw);if(parsed?.version===2&&parsed.sessions&&!Array.isArray(parsed.sessions))return warn(`[full-auto/state] Recovered from ${STATE_FILE3}.bak`),clearStateUnreadable(),{version:2,updatedAt:parsed.updatedAt??nowISO3(),oversightSequence:typeof parsed.oversightSequence==="number"?parsed.oversightSequence:0,sessions:sanitizeSessions(parsed.sessions)}}}catch(bakError){error48(`[full-auto/state] .bak recovery also failed: ${bakError instanceof Error?bakError.message:String(bakError)}`)}return markStateUnreadable2(`canonical=${reason}; .bak=missing-or-corrupt`),readCache.clear(),emptyPersisted2()}}function writePersisted2(directory,persisted){let filePath,tmpPath,bakPath,payload;try{ensureSwarmDir4(directory),filePath=validateSwarmPath(directory,STATE_FILE3),tmpPath=validateSwarmPath(directory,`${STATE_FILE3}.tmp`),bakPath=validateSwarmPath(directory,`${STATE_FILE3}.bak`),persisted.updatedAt=nowISO3(),payload=`${JSON.stringify(persisted,null,2)}
1573
- `}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to prepare ${STATE_FILE3} write: ${msg}`),Error(`Full-Auto state persistence prepare failed: ${msg}`)}try{if(fs41.existsSync(filePath))fs41.copyFileSync(filePath,bakPath)}catch{}try{fs41.writeFileSync(tmpPath,payload,"utf-8");try{let fd=fs41.openSync(tmpPath,"r+");try{fs41.fsyncSync(fd)}finally{fs41.closeSync(fd)}}catch{}fs41.renameSync(tmpPath,filePath),readCache.delete(filePath);let readback=fs41.readFileSync(filePath,"utf-8");if(JSON.parse(readback)?.version!==2)throw Error("Round-trip readback returned wrong version")}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to persist ${STATE_FILE3} atomically: ${msg}`),Error(`Full-Auto state persistence failed: ${msg}`)}}function loadFullAutoRunState(directory,sessionID){return readPersisted2(directory).sessions[sessionID]}function saveFullAutoRunState(directory,state){withStateLock(directory,()=>{let persisted=readPersisted2(directory);state.updatedAt=nowISO3(),persisted.sessions[state.sessionID]=state,writePersisted2(directory,persisted)})}function startFullAutoRun(directory,sessionID,config3,options={}){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),existing=persisted.sessions[sessionID],mode=config3?.mode??existing?.mode??"supervised",state=existing?{...existing,status:"running",mode,planID:options.planID??existing.planID,currentPhase:options.phase??existing.currentPhase,currentTaskID:options.taskID??existing.currentTaskID,pauseReason:void 0,terminateReason:void 0,updatedAt:nowISO3(),denialCounters:{consecutive:0,total:existing.denialCounters.total},consecutiveOversightFailures:0,counters:{...existing.counters,consecutiveOversightFailures:0}}:{...emptyState(sessionID,mode),status:"running",planID:options.planID,currentPhase:options.phase,currentTaskID:options.taskID};return persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function pauseFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="paused",state.pauseReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function disarmFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="idle",state.pauseReason=reason,state.terminateReason=void 0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function terminateFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="terminated",state.terminateReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function isFullAutoRunActive(directory,sessionID){return loadFullAutoRunState(directory,sessionID)?.status==="running"}function incrementFullAutoCounter(directory,sessionID,counter,delta=1){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.counters[counter]=(state.counters[counter]??0)+delta,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function incrementOversightFailureCounter(directory,sessionID){let result=0;return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=(state.counters.consecutiveOversightFailures??0)+1,state.consecutiveOversightFailures=state.counters.consecutiveOversightFailures,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),result=state.counters.consecutiveOversightFailures}),result}function resetOversightFailureCounter(directory,sessionID){withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=0,state.consecutiveOversightFailures=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted)})}function recordFullAutoDenial(directory,sessionID,denial){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;if(state.denialCounters.consecutive+=1,state.denialCounters.total+=1,state.denialHistory.push({timestamp:nowISO3(),tool:denial.tool,code:denial.code,reason:denial.reason}),state.denialHistory.length>MAX_DENIAL_HISTORY)state.denialHistory.splice(0,state.denialHistory.length-MAX_DENIAL_HISTORY);return state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function resetFullAutoDenials(directory,sessionID){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.denialCounters.consecutive=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function nextFullAutoOversightSequence(directory){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),next=(persisted.oversightSequence??0)+1;return persisted.oversightSequence=next,writePersisted2(directory,persisted),next})}function recordFullAutoOversight(directory,sessionID,verdict,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastOversightAt=nowISO3(),state.lastOversightVerdict=verdict,state.lastOversightReason=reason,state.counters.oversightChecks+=1,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function shouldPauseForDenials(state,config3){let denials=config3?.denials??{},maxConsecutive=denials.max_consecutive??3,maxTotal=denials.max_total??20,onLimit=denials.on_limit??"pause";if(state.denialCounters.consecutive>=maxConsecutive)return{pause:!0,reason:`denial-limit:consecutive>=${maxConsecutive}`,mode:onLimit};if(state.denialCounters.total>=maxTotal)return{pause:!0,reason:`denial-limit:total>=${maxTotal}`,mode:onLimit};return{pause:!1}}var import_proper_lockfile8,lockfile8,STATE_FILE3="full-auto-state.json",MAX_DENIAL_HISTORY=100,VALID_RUN_MODES,VALID_RUN_STATUSES,stateUnreadable=!1,stateUnreadableReason="",readCache;var init_state3=__esm(()=>{init_utils2();init_logger();import_proper_lockfile8=__toESM(require_proper_lockfile(),1),lockfile8=import_proper_lockfile8.default;VALID_RUN_MODES=new Set(["assisted","supervised","strict"]),VALID_RUN_STATUSES=new Set(["idle","running","paused","terminated"]);readCache=new Map});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
1573
+ `}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to prepare ${STATE_FILE3} write: ${msg}`),Error(`Full-Auto state persistence prepare failed: ${msg}`)}try{if(fs41.existsSync(filePath))fs41.copyFileSync(filePath,bakPath)}catch{}try{fs41.writeFileSync(tmpPath,payload,"utf-8");try{let fd=fs41.openSync(tmpPath,"r+");try{fs41.fsyncSync(fd)}finally{fs41.closeSync(fd)}}catch{}fs41.renameSync(tmpPath,filePath),readCache.delete(filePath);let readback=fs41.readFileSync(filePath,"utf-8");if(JSON.parse(readback)?.version!==2)throw Error("Round-trip readback returned wrong version")}catch(error93){let msg=error93 instanceof Error?error93.message:String(error93);throw error48(`[full-auto/state] Failed to persist ${STATE_FILE3} atomically: ${msg}`),Error(`Full-Auto state persistence failed: ${msg}`)}}function loadFullAutoRunState(directory,sessionID){return readPersisted2(directory).sessions[sessionID]}function saveFullAutoRunState(directory,state){withStateLock(directory,()=>{let persisted=readPersisted2(directory);state.updatedAt=nowISO3(),persisted.sessions[state.sessionID]=state,writePersisted2(directory,persisted)})}function startFullAutoRun(directory,sessionID,config3,options={}){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),existing=persisted.sessions[sessionID],mode=config3?.mode??existing?.mode??"supervised",state=existing?{...existing,status:"running",mode,planID:options.planID??existing.planID,currentPhase:options.phase??existing.currentPhase,currentTaskID:options.taskID??existing.currentTaskID,pauseReason:void 0,terminateReason:void 0,updatedAt:nowISO3(),denialCounters:{consecutive:0,total:existing.denialCounters.total},consecutiveOversightFailures:0,counters:{...existing.counters,consecutiveOversightFailures:0}}:{...emptyState(sessionID,mode),status:"running",planID:options.planID,currentPhase:options.phase,currentTaskID:options.taskID};return persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function pauseFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="paused",state.pauseReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function disarmFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="idle",state.pauseReason=reason,state.terminateReason=void 0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function terminateFullAutoRun(directory,sessionID,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.status="terminated",state.terminateReason=reason,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function isFullAutoRunActive(directory,sessionID){return loadFullAutoRunState(directory,sessionID)?.status==="running"}function incrementFullAutoCounter(directory,sessionID,counter,delta=1){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.counters[counter]=(state.counters[counter]??0)+delta,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function incrementOversightFailureCounter(directory,sessionID){let result=0;return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=(state.counters.consecutiveOversightFailures??0)+1,state.consecutiveOversightFailures=state.counters.consecutiveOversightFailures,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),result=state.counters.consecutiveOversightFailures}),result}function resetOversightFailureCounter(directory,sessionID){withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;state.counters.consecutiveOversightFailures=0,state.consecutiveOversightFailures=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted)})}function recordFullAutoDenial(directory,sessionID,denial){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;if(state.denialCounters.consecutive+=1,state.denialCounters.total+=1,state.denialHistory.push({timestamp:nowISO3(),tool:denial.tool,code:denial.code,reason:denial.reason}),state.denialHistory.length>MAX_DENIAL_HISTORY)state.denialHistory.splice(0,state.denialHistory.length-MAX_DENIAL_HISTORY);return state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function resetFullAutoDenials(directory,sessionID){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.denialCounters.consecutive=0,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function nextFullAutoOversightSequence(directory){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),next=(persisted.oversightSequence??0)+1;return persisted.oversightSequence=next,writePersisted2(directory,persisted),next})}function recordFullAutoOversight(directory,sessionID,verdict,reason){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastOversightAt=nowISO3(),state.lastOversightVerdict=verdict,state.lastOversightReason=reason,state.counters.oversightChecks+=1,state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function recordFullAutoEscalation(directory,sessionID,detail){return withStateLock(directory,()=>{let persisted=readPersisted2(directory),state=persisted.sessions[sessionID];if(!state)return;return state.lastEscalation={reason:detail.reason,interactionCount:detail.interactionCount,deadlockCount:detail.deadlockCount,phase:detail.phase,escalatedAt:nowISO3()},state.updatedAt=nowISO3(),persisted.sessions[sessionID]=state,writePersisted2(directory,persisted),state})}function shouldPauseForDenials(state,config3){let denials=config3?.denials??{},maxConsecutive=denials.max_consecutive??3,maxTotal=denials.max_total??20,onLimit=denials.on_limit??"pause";if(state.denialCounters.consecutive>=maxConsecutive)return{pause:!0,reason:`denial-limit:consecutive>=${maxConsecutive}`,mode:onLimit};if(state.denialCounters.total>=maxTotal)return{pause:!0,reason:`denial-limit:total>=${maxTotal}`,mode:onLimit};return{pause:!1}}var import_proper_lockfile8,lockfile8,STATE_FILE3="full-auto-state.json",MAX_DENIAL_HISTORY=100,VALID_RUN_MODES,VALID_RUN_STATUSES,stateUnreadable=!1,stateUnreadableReason="",readCache;var init_state3=__esm(()=>{init_utils2();init_logger();import_proper_lockfile8=__toESM(require_proper_lockfile(),1),lockfile8=import_proper_lockfile8.default;VALID_RUN_MODES=new Set(["assisted","supervised","strict"]),VALID_RUN_STATUSES=new Set(["idle","running","paused","terminated"]);readCache=new Map});function isValidMode(value){return VALID_MODES.includes(value)}async function handleFullAutoCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Full-Auto Mode requires an active session. Use /swarm-full-auto from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Full-Auto Mode requires an active session to operate.";let arg=args2[0]?.toLowerCase();if(arg==="status")return buildStatusReport(directory,sessionID,session.fullAutoMode);let newFullAutoMode,modeOverride;if(arg==="on"){newFullAutoMode=!0;let modeArg=args2[1]?.toLowerCase();if(modeArg){if(!isValidMode(modeArg))return`Error: invalid Full-Auto mode '${args2[1]}'. Valid modes: ${VALID_MODES.join(", ")}.`;modeOverride=modeArg}}else if(arg==="off")newFullAutoMode=!1;else if(arg&&isValidMode(arg))newFullAutoMode=!0,modeOverride=arg;else newFullAutoMode=!session.fullAutoMode;let v2Status="unavailable",modeLabel="supervised",denialMaxConsecutive=3,denialMaxTotal=20,failClosed=!0,durableError,criticModelAdvisory="";try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory),fullAutoConfig=config3.full_auto;if(newFullAutoMode&&configHadErrors)return"Error: Full-Auto Mode cannot be enabled — a swarm plugin config file exists but could not be loaded, so full_auto.locked cannot be verified. Fix the config file (see warnings above) and retry.";if(newFullAutoMode&&fullAutoConfig?.locked===!0)return"Error: Full-Auto Mode is locked for this project (full_auto.locked is true in the swarm plugin config). Runtime activation is disabled by configuration; remove the lock to use /swarm full-auto on.";let effectiveMode=modeOverride??fullAutoConfig?.mode??"supervised";if(modeLabel=effectiveMode,denialMaxConsecutive=fullAutoConfig?.denials?.max_consecutive??3,denialMaxTotal=fullAutoConfig?.denials?.max_total??20,failClosed=fullAutoConfig?.fail_closed!==!1,newFullAutoMode){startFullAutoRun(directory,sessionID,fullAutoConfig?{...fullAutoConfig,mode:effectiveMode}:void 0),v2Status="running";let criticModel=fullAutoConfig?.critic_model??config3.agents?.critic?.model,architectModel=config3.agents?.architect?.model;if(criticModel&&architectModel&&criticModel===architectModel)criticModelAdvisory=" WARNING: critic model matches architect model — set full_auto.critic_model (or agents.critic.model) to a different model for independent oversight."}else{if(!disarmFullAutoRun(directory,sessionID,"/swarm full-auto off"))terminateFullAutoRun(directory,sessionID,"never started");v2Status="idle"}}catch(error93){durableError=error93 instanceof Error?error93.message:String(error93),error48(`[full-auto] durable run-state write failed: ${durableError}`)}if(newFullAutoMode&&durableError)return["Error: Full-Auto Mode could NOT be enabled — durable run-state write failed.",`Reason: ${durableError}.`,"Inspect .swarm/ permissions and disk space, then retry."].join(" ");if(session.fullAutoMode=newFullAutoMode,!newFullAutoMode)session.fullAutoInteractionCount=0,session.fullAutoDeadlockCount=0,session.fullAutoLastQuestionHash=null;if(!newFullAutoMode)return["Full-Auto Mode disabled",`(v2 run-state: ${v2Status}; mode=${modeLabel})`].join(" ");return["Full-Auto Mode enabled",`(v2 mode=${modeLabel}, fail_closed=${failClosed},`,`denials max ${denialMaxConsecutive} consecutive / ${denialMaxTotal} total)`].join(" ")+criticModelAdvisory}function buildStatusReport(directory,sessionID,sessionFlag){let lines=[];lines.push(`Full-Auto session flag: ${sessionFlag?"on":"off"}`);try{let{config:config3,configHadErrors}=loadPluginConfigWithMeta(directory);if(configHadErrors)lines.push("Config: UNREADABLE (a config file exists but could not be loaded; `full_auto.locked` cannot be verified, so runtime activation refuses by fail-closed default). Fix the config file to restore normal status.");if(config3.full_auto?.locked===!0)lines.push("Config: locked (runtime activation disabled via full_auto.locked)")}catch{}try{let runState=loadFullAutoRunState(directory,sessionID),stateHealth=isFullAutoStateUnreadable();if(stateHealth.unreadable)lines.push(`Durable run-state: UNREADABLE (${stateHealth.reason}). Non-read-only tools are blocked fail-closed until .swarm/full-auto-state.json (or .bak) is restored or deleted.`);else if(!runState)lines.push("Durable run-state: none (no Full-Auto run for this session)");else{if(lines.push(`Durable run-state: ${runState.status} (mode=${runState.mode})`),runState.pauseReason)lines.push(`Pause reason: ${runState.pauseReason}`);if(runState.terminateReason)lines.push(`Terminate reason: ${runState.terminateReason}`);if(lines.push(`Counters: ${runState.counters.toolCalls} tool calls, ${runState.counters.architectTurns} architect turns, ${runState.counters.oversightChecks} oversight checks`),lines.push(`Denials: ${runState.denialCounters.consecutive} consecutive / ${runState.denialCounters.total} total`),runState.lastOversightVerdict)lines.push(`Last oversight verdict: ${runState.lastOversightVerdict}${runState.lastOversightAt?` at ${runState.lastOversightAt}`:""}`)}}catch(error93){lines.push(`Durable run-state: unreadable (${error93 instanceof Error?error93.message:String(error93)})`)}return lines.join(`
1574
1574
  `)}var VALID_MODES;var init_full_auto=__esm(()=>{init_config();init_state3();init_state2();init_logger();VALID_MODES=["assisted","supervised","strict"]});function escapeHtml(str){return str.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#39;")}function sanitizeString(str,maxLength){if(!str)return"";let sanitized=String(str).replace(RTL_OVERRIDE_PATTERN,"");if(sanitized.length>maxLength)return`${sanitized.substring(0,maxLength-3)}...`;return sanitized}function validatePlanPhases(plan){if(!plan||typeof plan!=="object")return!1;let p=plan;if(!Array.isArray(p.phases))return!1;for(let phase of p.phases){if(!phase||typeof phase!=="object")return!1;if(!Array.isArray(phase.tasks))return!1}return!0}function extractCurrentPhaseFromPlan2(plan){if(!plan)return{currentPhase:null,currentTask:null,incompleteTasks:[]};if(!_internals57.validatePlanPhases(plan))return{currentPhase:null,currentTask:null,incompleteTasks:[]};let currentPhase=null,currentPhaseNum=plan.current_phase;if(currentPhaseNum){let phase=plan.phases.find((p)=>p.id===currentPhaseNum);currentPhase=phase?`Phase ${phase.id}: ${phase.name}`:null}else{let inProgressPhase=plan.phases.find((p)=>p.status==="in_progress");if(inProgressPhase)currentPhase=`Phase ${inProgressPhase.id}: ${inProgressPhase.name}`;else if(plan.phases.length>0)currentPhase=`Phase ${plan.phases[0].id}: ${plan.phases[0].name}`}let currentTask=null,incompleteTasks=[];for(let phase of plan.phases)for(let task of phase.tasks){if(task.status==="in_progress")currentTask=sanitizeString(task.id,MAX_TASK_ID_LENGTH);if(task.status!=="completed"){if(incompleteTasks.length<MAX_INCOMPLETE_TASKS)incompleteTasks.push(sanitizeString(task.id,MAX_TASK_ID_LENGTH))}}if(!currentTask&&incompleteTasks.length>0)currentTask=incompleteTasks[0];return{currentPhase,currentTask,incompleteTasks}}function parseSessionState(content){if(!content)return null;try{let state=JSON.parse(content),activeAgent=null;if(state.activeAgent&&typeof state.activeAgent==="object"){let entries=Object.entries(state.activeAgent);if(entries.length>0)activeAgent=sanitizeString(entries[entries.length-1][1],MAX_TASK_ID_LENGTH)}let delegationState=null;if(state.delegationChains&&typeof state.delegationChains==="object"){let chains=Object.entries(state.delegationChains),activeChains=[],maxDepth=0;for(let[,chain]of chains)if(Array.isArray(chain)&&chain.length>0){let sanitizedChain=chain.map((e)=>`${sanitizeString(e.from,MAX_TASK_ID_LENGTH)}->${sanitizeString(e.to,MAX_TASK_ID_LENGTH)}`).join(" | ");activeChains.push(sanitizedChain),maxDepth=Math.max(maxDepth,chain.length)}if(activeChains.length>0)delegationState={activeChains,delegationDepth:maxDepth,pendingHandoffs:[]}}let pendingQA=null;if(state.agentSessions&&typeof state.agentSessions==="object")for(let[,session]of Object.entries(state.agentSessions)){let sess=session;if(sess.lastGateFailure&&sess.currentTaskId){pendingQA={taskId:sanitizeString(sess.lastGateFailure.taskId,MAX_TASK_ID_LENGTH),lastFailure:sanitizeString(sess.lastGateFailure.tool,MAX_TASK_ID_LENGTH)};break}}return{activeAgent,delegationState,pendingQA}}catch(error93){return log("[HandoffService] state extraction failed",{error:error93 instanceof Error?error93.message:String(error93)}),null}}function extractDecisions2(content){if(!content)return[];let decisions=[],lines=content.split(`
1575
1575
  `),inDecisionsSection=!1;for(let line of lines){if(line.trim()==="## Decisions"){inDecisionsSection=!0;continue}if(inDecisionsSection&&line.startsWith("## ")&&line.trim()!=="## Decisions")break;if(inDecisionsSection&&line.trim().startsWith("- ")){let cleaned=line.trim().substring(2).replace(/\s*\[.*?\]\s*/g,"").replace(/✅/g,"").replace(/\[confirmed\]/g,"").trim();if(cleaned){let sanitized=sanitizeString(cleaned,MAX_DECISION_LENGTH);if(sanitized)decisions.push(sanitized)}}}return decisions.slice(-5)}function extractPhaseMetrics(content){if(!content)return"";let lines=content.split(`
1576
1576
  `),inPhaseMetrics=!1,metricsLines=[];for(let line of lines){if(line.trim()==="## Phase Metrics"){inPhaseMetrics=!0;continue}if(inPhaseMetrics&&line.startsWith("## "))break;if(inPhaseMetrics)metricsLines.push(line)}return metricsLines.slice(-5).join(`
@@ -1605,7 +1605,7 @@ ${markdown}`}}var HANDOFF_SOURCE_SESSION_PREFIX="<!-- opencode-swarm-handoff-sou
1605
1605
 
1606
1606
  ${USAGE3}`;let issueUrl=`https://github.com/${issueInfo.owner}/${issueInfo.repo}/issues/${issueInfo.number}`,result=validateAndSanitizeUrl(issueUrl);if("error"in result)return`Error: ${result.error}
1607
1607
 
1608
- ${USAGE3}`;let flags=[];if(parsed.plan)flags.push("plan=true");if(parsed.trace)flags.push("trace=true");if(parsed.noRepro)flags.push("noRepro=true");let flagsStr=flags.length>0?` ${flags.join(" ")}`:"";return`[MODE: ISSUE_INGEST issue="${result.sanitized}"${flagsStr}]`}var USAGE3;var init_issue=__esm(()=>{init_url_security();USAGE3=["Usage: /swarm issue <url|owner/repo#N|N> [--plan] [--trace] [--no-repro]","","Ingest a GitHub issue into the swarm workflow."," /swarm issue https://github.com/owner/repo/issues/42"," /swarm issue owner/repo#42"," /swarm issue 42 --plan"," /swarm issue 42 --trace --no-repro","","Flags:"," --plan Transition to plan creation after spec generation"," --trace Run full fix-and-PR workflow (implies --plan)"," --no-repro Skip reproduction step"].join(`
1608
+ ${USAGE3}`;let flags=[];if(parsed.plan)flags.push("plan=true");if(parsed.trace)flags.push("trace=true");if(parsed.noRepro)flags.push("noRepro=true");let flagsStr=flags.length>0?` ${flags.join(" ")}`:"";return`[MODE: ISSUE_INGEST issue="${result.sanitized}"${flagsStr}]`}var USAGE3;var init_issue=__esm(()=>{init_url_security();USAGE3=["Usage: /swarm issue <url|owner/repo#N|N> [--plan] [--trace] [--no-repro]","","Ingest a GitHub issue into the swarm workflow."," /swarm issue https://github.com/owner/repo/issues/42"," /swarm issue owner/repo#42"," /swarm issue 42 --plan"," /swarm issue 42 --trace --no-repro","","Flags:"," --plan Transition to plan creation after spec generation"," --trace Run the fix workflow end-to-end (implies --plan); compose commit-pr to publish."," --no-repro Skip reproduction step"].join(`
1609
1609
  `)});import{randomUUID as randomUUID9}from"node:crypto";import{existsSync as existsSync51,readFileSync as readFileSync31}from"node:fs";import{mkdir as mkdir20,readFile as readFile23,writeFile as writeFile18}from"node:fs/promises";import*as os20 from"node:os";import*as path91 from"node:path";async function migrateKnowledgeToExternal(_directory,_config){let externalSentinelPath=path91.join(_directory,".swarm",".knowledge-external-migrated"),contextPath=path91.join(_directory,".swarm","context.md");if(_internals60.existsSync(externalSentinelPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"external-sentinel-exists"};if(!_internals60.existsSync(contextPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"no-context-file"};let contextContent=await _internals60.readFile(contextPath,"utf-8");if(contextContent.trim().length===0)return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"empty-context"};let lines=contextContent.split(`
1610
1610
  `),entriesCount=0;for(let line of lines)if(line.trimStart().startsWith("- "))entriesCount++;return await _internals60.writeSentinel(externalSentinelPath,entriesCount,entriesCount),{migrated:!0,entriesMigrated:entriesCount,entriesDropped:0,entriesTotal:entriesCount}}async function migrateContextToKnowledge(directory,config3){let sentinelPath=path91.join(directory,".swarm",".knowledge-migrated"),contextPath=path91.join(directory,".swarm","context.md"),knowledgePath=resolveSwarmKnowledgePath(directory);if(existsSync51(sentinelPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"sentinel-exists"};if(!existsSync51(contextPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"no-context-file"};let contextContent=await readFile23(contextPath,"utf-8");if(contextContent.trim().length===0)return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"empty-context"};let rawEntries=_internals60.parseContextMd(contextContent);if(rawEntries.length===0)return await _internals60.writeSentinel(sentinelPath,0,0),{migrated:!0,entriesMigrated:0,entriesDropped:0,entriesTotal:0};let existing=await readKnowledge(knowledgePath),migrated=0,dropped=0,projectName=_internals60.inferProjectName(directory);for(let raw of rawEntries){if(config3.validation_enabled!==!1){let category=raw.categoryHint??_internals60.inferCategoryFromText(raw.text);if(!validateLesson(raw.text,existing.map((e)=>e.lesson),{category,scope:"global",confidence:0.3}).valid){dropped++;continue}}if(findNearDuplicate(raw.text,existing,config3.dedup_threshold??0.6)){dropped++;continue}let inferredTags=inferTags2(raw.text),entry={id:randomUUID9(),tier:"swarm",lesson:_internals60.truncateLesson(raw.text),category:raw.categoryHint??_internals60.inferCategoryFromText(raw.text),tags:[...inferredTags,`migration:${raw.sourceSection}`],scope:"global",confidence:0.3,status:"candidate",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:config3.schema_version??KNOWLEDGE_SCHEMA_VERSION,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),project_name:projectName,auto_generated:!0};existing.push(entry),migrated++}if(migrated>0)await rewriteKnowledge(knowledgePath,existing);return await _internals60.writeSentinel(sentinelPath,migrated,dropped),log(`[knowledge-migrator] Migrated ${migrated} entries, dropped ${dropped}`),{migrated:!0,entriesMigrated:migrated,entriesDropped:dropped,entriesTotal:rawEntries.length}}async function migrateHiveKnowledgeLegacy(config3){let legacyHivePath=_internals60.resolveLegacyHiveKnowledgePath(),canonicalHivePath=resolveHiveKnowledgePath(),sentinelPath=path91.join(path91.dirname(canonicalHivePath),".hive-knowledge-migrated");if(existsSync51(sentinelPath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"sentinel-exists"};if(!existsSync51(legacyHivePath))return{migrated:!1,entriesMigrated:0,entriesDropped:0,entriesTotal:0,skippedReason:"no-context-file"};let legacyEntries=await readKnowledge(legacyHivePath);if(legacyEntries.length===0)return await _internals60.writeSentinel(sentinelPath,0,0),{migrated:!0,entriesMigrated:0,entriesDropped:0,entriesTotal:0};let existingHiveEntries=await readKnowledge(canonicalHivePath),migrated=0,dropped=0,entryErrors=[];for(let legacyEntry of legacyEntries)try{let lesson=legacyEntry.lesson;if(!lesson||typeof lesson!=="string"||lesson.length<15){dropped++;continue}if(findNearDuplicate(lesson,existingHiveEntries,config3.dedup_threshold??0.6)){dropped++;continue}let category=legacyEntry.category||"process",validationResult=validateLesson(lesson,existingHiveEntries.map((e)=>e.lesson),{category,scope:"global",confidence:0.3});if(!validationResult.valid){let errorMsg=`Validation failed for legacy entry: ${validationResult.reason}`;entryErrors.push(errorMsg),warn(`[knowledge-migrator] ${errorMsg}`),dropped++;continue}let confidence=legacyEntry.confidence??0.8,scopeTag=legacyEntry.scope_tag||"global",legacyId=legacyEntry.id,existingIds=new Set(existingHiveEntries.map((e)=>e.id)),resolvedId=legacyId&&existingIds.has(legacyId)?randomUUID9():legacyId||randomUUID9();if(legacyId&&existingIds.has(legacyId))warn(`[knowledge-migrator] Legacy entry ID collision for "${legacyId}", generating new UUID`);let newHiveEntry={id:resolvedId,tier:"hive",lesson:_internals60.truncateLesson(lesson),category,tags:["migration:legacy-hive"],scope:scopeTag,confidence:Math.min(Math.max(confidence,0),1),status:"established",confirmed_by:[],retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:KNOWLEDGE_SCHEMA_VERSION,created_at:legacyEntry.created_at||new Date().toISOString(),updated_at:legacyEntry.updated_at||new Date().toISOString(),source_project:"legacy-promotion",encounter_score:1};try{await _internals60.appendKnowledge(canonicalHivePath,newHiveEntry),existingHiveEntries.push(newHiveEntry),migrated++}catch(appendError){let errorMsg=`Failed to append entry: ${appendError instanceof Error?appendError.message:String(appendError)}`;entryErrors.push(errorMsg),warn(`[knowledge-migrator] ${errorMsg}`),dropped++}}catch(entryError){let errorMsg=`Unexpected error processing legacy entry: ${entryError instanceof Error?entryError.message:String(entryError)}`;entryErrors.push(errorMsg),warn(`[knowledge-migrator] ${errorMsg}`),dropped++}return await _internals60.writeSentinel(sentinelPath,migrated,dropped),log(`[knowledge-migrator] Migrated ${migrated} legacy hive entries, dropped ${dropped}`),{migrated:!0,entriesMigrated:migrated,entriesDropped:dropped,entriesTotal:legacyEntries.length,...entryErrors.length>0&&{entryErrors}}}function parseContextMd(content){let sections=_internals60.splitIntoSections(content),entries=[],seen=new Set,sectionPatterns=[{pattern:/^#{1,3}\s+lessons?\s+learned/i,sourceSection:"lessons-learned"},{pattern:/^#{1,3}\s+patterns?/i,sourceSection:"patterns"},{pattern:/^#{1,3}\s+sme\s+cache/i,sourceSection:"sme-cache"},{pattern:/^#{1,3}\s+decisions?/i,sourceSection:"decisions"}];for(let section of sections){let match=sectionPatterns.find((sp)=>sp.pattern.test(section.heading));if(!match)continue;let bullets=_internals60.extractBullets(section.body);for(let bullet of bullets){if(bullet.length<15)continue;let normalized=normalize5(bullet);if(seen.has(normalized))continue;seen.add(normalized),entries.push({text:_internals60.truncateLesson(bullet),sourceSection:match.sourceSection,categoryHint:_internals60.inferCategoryFromText(bullet)})}}return entries}function splitIntoSections(content){let sections=[],headingRegex=/^(#{1,3})\s+(.+)/gm,matches=[],match=headingRegex.exec(content);while(match!==null)matches.push({index:match.index,heading:match[0]}),match=headingRegex.exec(content);for(let i=0;i<matches.length;i++){let current=matches[i],next=matches[i+1],bodyStart=current.index+current.heading.length,bodyEnd=next?next.index:content.length,body=content.slice(bodyStart,bodyEnd).trim();sections.push({heading:current.heading,body})}return sections}function extractBullets(body){let bullets=[],bulletRegex=/^\s*[-*]\s+(.+)/;for(let line of body.split(`
1611
1611
  `)){let match=line.match(bulletRegex);if(match)bullets.push(match[1].trim())}return bullets}function inferCategoryFromText(text){let lower=text.toLowerCase();if(/\b(?:test|spec|vitest|jest)\b/.test(lower))return"testing";if(/\b(?:security|auth|token|password|encrypt)\b/.test(lower))return"security";if(/\b(?:performance|latency|cache|throughput)\b/.test(lower))return"performance";if(/\b(?:architecture|design|pattern|structure)\b/.test(lower))return"architecture";if(/\b(?:debug|error|fix|bug|issue)\b/.test(lower))return"debugging";if(/\b(?:tool|config|setup|install|build)\b/.test(lower))return"tooling";if(/\b(?:integrate|api|hook|connect)\b/.test(lower))return"integration";if(/\b(?:process|workflow|step|approach)\b/.test(lower))return"process";return"other"}function truncateLesson2(text){if(text.length<=280)return text;return`${text.slice(0,277)}...`}function inferProjectName(directory){let packageJsonPath=path91.join(directory,"package.json");if(existsSync51(packageJsonPath))try{let pkg=JSON.parse(readFileSync31(packageJsonPath,"utf-8"));if(pkg.name&&typeof pkg.name==="string")return pkg.name}catch{}return path91.basename(directory)}async function writeSentinel(sentinelPath,migrated,dropped){let sentinel={migrated_at:new Date().toISOString(),source_version:"6.16",target_version:"6.17",entries_migrated:migrated,entries_dropped:dropped,schema_version:1,migration_tool:"knowledge-migrator.ts"};await _internals60.mkdir(path91.dirname(sentinelPath),{recursive:!0}),await _internals60.writeFile(sentinelPath,JSON.stringify(sentinel,null,2),"utf-8")}function resolveLegacyHiveKnowledgePath(){let platform=process.platform,home=process.env.HOME||os20.homedir(),dataDir;if(platform==="win32")dataDir=path91.join(process.env.LOCALAPPDATA||path91.join(home,"AppData","Local"),"opencode-swarm","Data");else if(platform==="darwin")dataDir=path91.join(home,"Library","Application Support","opencode-swarm");else dataDir=path91.join(process.env.XDG_DATA_HOME||path91.join(home,".local","share"),"opencode-swarm");return path91.join(dataDir,"hive-knowledge.jsonl")}var _internals60;var init_knowledge_migrator=__esm(()=>{init_logger();init_knowledge_store();init_knowledge_types();init_knowledge_validator();_internals60={appendKnowledge,migrateContextToKnowledge,migrateKnowledgeToExternal,migrateHiveKnowledgeLegacy,parseContextMd,splitIntoSections,extractBullets,inferCategoryFromText,truncateLesson:truncateLesson2,inferProjectName,writeSentinel,resolveLegacyHiveKnowledgePath,existsSync:existsSync51,readFileSync:readFileSync31,readFile:readFile23,mkdir:mkdir20,writeFile:writeFile18}});import{join as join73}from"node:path";function resolveEntryByPrefix(entries,inputId){let exact=entries.find((e)=>e.id===inputId);if(exact)return{entry:exact};let matches=entries.filter((e)=>e.id.startsWith(inputId));if(matches.length===0)return{error:`No entry found matching '${inputId}'.`};if(matches.length===1)return{entry:matches[0]};let candidates=matches.map((e)=>e.id).join(`
@@ -1709,7 +1709,7 @@ ${stackPrefix}`;return INFRASTRUCTURE_FAILURE_PATTERNS.some((pattern)=>pattern.t
1709
1709
  `)){let trimmed=line.trim();if(!trimmed.startsWith("{")||!trimmed.endsWith("}"))continue;try{let parsed=JSON.parse(trimmed),testResults=parseJestLikeJsonTestResults(parsed);if(testResults.length>0)return testResults}catch{}}if(framework==="bun")return parseBunJsonLines(output);return[]}function parseTestOutput2(framework,output){let totals={passed:0,failed:0,skipped:0,total:0},coveragePercent;switch(framework){case"vitest":case"jest":case"bun":{let jsonMatch=output.match(/\{[\s\S]*"testResults"[\s\S]*\}/);if(jsonMatch)try{let parsed=JSON.parse(jsonMatch[0]);if(parsed.numTotalTests!==void 0)totals.passed=parsed.numPassedTests||0,totals.failed=parsed.numFailedTests||0,totals.skipped=parsed.numPendingTests||0,totals.total=parsed.numTotalTests||0;if(parsed.coverage!==void 0)coveragePercent=parsed.coverage}catch{}if(totals.total===0){let passMatch=output.match(/(\d+)\s+pass(ing|ed)?/),failMatch=output.match(/(\d+)\s+fail(ing|ed)?/),skipMatch=output.match(/(\d+)\s+skip(ping|ped)?/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped}let coverageMatch=output.match(/All files[^\d]*(\d+\.?\d*)\s*%/);if(!coveragePercent&&coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"mocha":{let passMatch=output.match(/(\d+)\s+passing/),failMatch=output.match(/(\d+)\s+failing/),pendingMatch=output.match(/(\d+)\s+pending/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(pendingMatch)totals.skipped=parseInt(pendingMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"pytest":{let passMatch=output.match(/(\d+)\s+passed/),failMatch=output.match(/(\d+)\s+failed/),skipMatch=output.match(/(\d+)\s+skipped/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;let coverageMatch=output.match(/TOTAL\s+(\d+\.?\d*)\s*%/);if(coverageMatch)coveragePercent=parseFloat(coverageMatch[1]);break}case"cargo":{let passMatch=output.match(/test result: ok\. (\d+) passed/),failMatch=output.match(/test result: FAILED\. (\d+) passed; (\d+) failed/);if(failMatch)totals.passed=parseInt(failMatch[1],10),totals.failed=parseInt(failMatch[2],10);else if(passMatch)totals.passed=parseInt(passMatch[1],10);totals.total=totals.passed+totals.failed;break}case"pester":{let passMatch=output.match(/Passed:\s*(\d+)/),failMatch=output.match(/Failed:\s*(\d+)/),skipMatch=output.match(/Skipped:\s*(\d+)/);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"go-test":{let passMatches=[...output.matchAll(/--- PASS:/g)],failMatches=[...output.matchAll(/--- FAIL:/g)],skipMatches=[...output.matchAll(/--- SKIP:/g)];totals.passed=passMatches.length,totals.failed=failMatches.length,totals.skipped=skipMatches.length,totals.total=totals.passed+totals.failed+totals.skipped;let covMatch=output.match(/coverage:\s*(\d+\.?\d*)\s*%/);if(covMatch)coveragePercent=parseFloat(covMatch[1]);break}case"maven":{let mavenMatch=output.match(/Tests run:\s*(\d+),\s*Failures:\s*(\d+),\s*Errors:\s*(\d+),\s*Skipped:\s*(\d+)/);if(mavenMatch){let total=parseInt(mavenMatch[1],10),failures=parseInt(mavenMatch[2],10),errors5=parseInt(mavenMatch[3],10),skipped=parseInt(mavenMatch[4],10);totals.failed=failures+errors5,totals.skipped=skipped,totals.passed=total-totals.failed-skipped,totals.total=total}break}case"gradle":{let gradleMatch=output.match(/(\d+) tests? completed(?:,\s*(\d+) failed)?(?:,\s*(\d+) skipped)?/);if(gradleMatch)totals.total=parseInt(gradleMatch[1],10),totals.failed=gradleMatch[2]?parseInt(gradleMatch[2],10):0,totals.skipped=gradleMatch[3]?parseInt(gradleMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"dotnet-test":{let passMatch=output.match(/Passed[!:]?\s*(\d+)/i),failMatch=output.match(/Failed[!:]?\s*(\d+)/i),skipMatch=output.match(/Skipped[!:]?\s*(\d+)/i);if(passMatch)totals.passed=parseInt(passMatch[1],10);if(failMatch)totals.failed=parseInt(failMatch[1],10);if(skipMatch)totals.skipped=parseInt(skipMatch[1],10);totals.total=totals.passed+totals.failed+totals.skipped;break}case"ctest":{let ctestMatch=output.match(/(\d+) tests? failed out of (\d+)/);if(ctestMatch)totals.failed=parseInt(ctestMatch[1],10),totals.total=parseInt(ctestMatch[2],10),totals.passed=totals.total-totals.failed;else{let allPassMatch=output.match(/100% tests passed.*?(\d+) tests?/);if(allPassMatch)totals.total=parseInt(allPassMatch[1],10),totals.passed=totals.total}break}case"swift-test":{let swiftMatch=output.match(/Executed (\d+) tests?,\s*with (\d+) failures?/);if(swiftMatch)totals.total=parseInt(swiftMatch[1],10),totals.failed=parseInt(swiftMatch[2],10),totals.passed=totals.total-totals.failed;break}case"dart-test":{let dartPassMatch=output.match(/\+(\d+):\s*All tests passed/),dartMixMatch=output.match(/\+(\d+)\s+-(\d+):/);if(dartPassMatch)totals.passed=parseInt(dartPassMatch[1],10),totals.total=totals.passed;else if(dartMixMatch)totals.passed=parseInt(dartMixMatch[1],10),totals.failed=parseInt(dartMixMatch[2],10),totals.total=totals.passed+totals.failed;break}case"rspec":{let rspecMatch=output.match(/(\d+) examples?,\s*(\d+) failures?(?:,\s*(\d+) pending)?/);if(rspecMatch)totals.total=parseInt(rspecMatch[1],10),totals.failed=parseInt(rspecMatch[2],10),totals.skipped=rspecMatch[3]?parseInt(rspecMatch[3],10):0,totals.passed=totals.total-totals.failed-totals.skipped;break}case"minitest":{let minitestMatch=output.match(/(\d+) runs?,\s*\d+ assertions?,\s*(\d+) failures?,\s*(\d+) errors?,\s*(\d+) skips?/);if(minitestMatch)totals.total=parseInt(minitestMatch[1],10),totals.failed=parseInt(minitestMatch[2],10)+parseInt(minitestMatch[3],10),totals.skipped=parseInt(minitestMatch[4],10),totals.passed=totals.total-totals.failed-totals.skipped;break}case"pest":case"phpunit":case"php-artisan":{let phpunitMatch=output.match(/Tests:\s*(\d+),\s*Assertions:\s*\d+(?:,\s*Failures:\s*(\d+))?(?:,\s*Errors:\s*(\d+))?(?:,\s*Skipped:\s*(\d+))?/),okMatch=output.match(/OK\s*\((\d+)\s+tests?/);if(phpunitMatch){totals.total=parseInt(phpunitMatch[1],10);let failures=phpunitMatch[2]?parseInt(phpunitMatch[2],10):0,errors5=phpunitMatch[3]?parseInt(phpunitMatch[3],10):0;totals.skipped=phpunitMatch[4]?parseInt(phpunitMatch[4],10):0,totals.failed=failures+errors5,totals.passed=totals.total-totals.failed-totals.skipped}else if(okMatch)totals.total=parseInt(okMatch[1],10),totals.passed=totals.total;break}default:break}return{totals,coveragePercent}}async function readBoundedStream2(stream,maxBytes){let reader=stream.getReader(),chunks=[],totalBytes=0,truncated=!1;try{while(!0){let{done,value}=await reader.read();if(done)break;if(totalBytes+value.length>maxBytes){let remaining=maxBytes-totalBytes;if(remaining>0)chunks.push(value.slice(0,remaining));totalBytes=maxBytes,truncated=!0,reader.cancel().catch(()=>{});break}chunks.push(value),totalBytes+=value.length}}catch{}finally{try{reader.releaseLock()}catch{}}let decoder=new TextDecoder("utf-8",{fatal:!1}),combined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)combined.set(chunk,offset),offset+=chunk.length;return{text:decoder.decode(combined),truncated}}async function runTests(framework,scope,files,coverage,timeout_ms,cwd,bail){if(scope!=="all"&&files.length>0){let unsupportedReason=getTargetedExecutionUnsupportedReason(framework);if(unsupportedReason)return{success:!1,framework,scope,error:`Framework "${framework}" does not support targeted test-file execution`,message:`The resolved test selection cannot be run safely because ${unsupportedReason}. Use a framework-native selector manually or let the architect handle the broader sweep.`,outcome:"error"}}let command=process.env.SWARM_LANG_BACKEND!=="legacy"?await buildTestCommandViaDispatch(framework,scope,files,coverage,cwd,bail)??buildTestCommand2(framework,scope,files,coverage,cwd,bail):buildTestCommand2(framework,scope,files,coverage,cwd,bail);if(!command)return{success:!1,framework,scope,error:`No test command available for framework: ${framework}`,message:"Install a supported test framework to run tests",outcome:"error"};if(command.join(" ").length>MAX_COMMAND_LENGTH2)return{success:!1,framework,scope,command,error:"Command exceeds maximum allowed length",outcome:"error"};let startTime=Date.now(),vitestJsonOutputPath=framework==="vitest"?path112.join(cwd,".swarm","cache","test-runner-vitest.json"):void 0;try{if(vitestJsonOutputPath)try{if(fs56.mkdirSync(path112.dirname(vitestJsonOutputPath),{recursive:!0}),fs56.existsSync(vitestJsonOutputPath))fs56.unlinkSync(vitestJsonOutputPath)}catch{}let proc=bunSpawn(command,{stdout:"pipe",stderr:"pipe",cwd}),timeoutPromise=new Promise((resolve45)=>setTimeout(()=>{proc.kill(),resolve45(-1)},timeout_ms)),[exitCode,stdoutResult,stderrResult]=await Promise.all([Promise.race([proc.exited,timeoutPromise]),readBoundedStream2(proc.stdout,MAX_OUTPUT_BYTES3),readBoundedStream2(proc.stderr,MAX_OUTPUT_BYTES3)]),duration_ms=Date.now()-startTime,output=stdoutResult.text;if(stderrResult.text)output+=(output?`
1710
1710
  `:"")+stderrResult.text;if(vitestJsonOutputPath)try{if(fs56.existsSync(vitestJsonOutputPath)){let vitestJsonOutput=fs56.readFileSync(vitestJsonOutputPath,"utf-8");if(vitestJsonOutput.trim().length>0)output+=(output?`
1711
1711
  `:"")+vitestJsonOutput}}catch{}if(stdoutResult.truncated||stderrResult.truncated)output+=`
1712
- ... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,cwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=exitCode===-1;if(exitCode===0&&totals.failed===0){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;if(result.message=`${framework} tests passed (${totals.passed}/${totals.total})`,coveragePercent!==void 0)result.message+=` with ${coveragePercent}% coverage`;return result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path112.isAbsolute(testFile))return normalized;let relative23=path112.relative(workingDir,testFile);if(relative23.startsWith("..")||path112.isAbsolute(relative23))return normalized;return relative23.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now=new Date().toISOString(),changedFiles=(sourceFiles&&sourceFiles.length>0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES3=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS=60000,MAX_TIMEOUT_MS=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with framework detection. Supports bun, vitest, jest, mocha, pytest, cargo, pester, go-test, maven, gradle, dotnet-test, ctest, swift-test, dart-test, rspec, and minitest. Returns deterministic normalized JSON with framework, scope, command, totals, coverage, duration, success status, and failures. Use scope "all" for full suite, "convention" to accept direct test files or map source files to test files, "graph" to find related tests via imports from source files, or "impact" to find tests covering changed source files using test-impact analysis.',args:{scope:exports_external.enum(["all","convention","graph","impact"]).optional().describe('Test scope: "all" runs full suite, "convention" accepts direct test files or maps source files to tests by naming, "graph" finds related tests via imports from source files, "impact" finds tests covering changed source files via test-impact analysis'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),allow_full_suite:exports_external.boolean().optional().describe('Explicit opt-in for scope "all". Required because full-suite output can destabilize SSE streaming.'),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", or "impact"; files must be array of strings; coverage must be boolean; timeout_ms must be a positive number',outcome:"error"},null,2);let scope=args2.scope||"all";if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files array - omitting files causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS,MAX_TIMEOUT_MS),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path112.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path112.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path112.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath=path112.relative(workingDir,absPath);return path112.isAbsolute(relativePath)?absPath:relativePath});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&testFiles.length===0){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,workingDir,bail);recordAndAnalyzeResults(result,testFiles,workingDir,_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}})});import*as fs57 from"node:fs";import*as path113 from"node:path";function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path113.normalize(dir);return path113.isAbsolute(normalized)?normalized:path113.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path113.join(dir,"package.json");if(fs57.existsSync(packagePath)){let content=fs57.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path113.join(dir,"CHANGELOG.md");if(fs57.existsSync(changelogPath)){let match=fs57.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path113.join(dir,file3);if(fs57.existsSync(filePath))try{let match=fs57.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals76.getPackageVersion(dir),changelogVersion=_internals76.getChangelogVersion(dir),versionFileVersion=_internals76.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if(result.findings&&result.findings.length>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;return{type:"secrets",status:"fail",message:`Found ${result.findings.length} secret(s): ${critical} critical, ${high} high`,details:{count:result.count,critical,high,filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(coverage.exists)return{type:"req_coverage",status:"pass",message:"Requirement coverage report found",details:{path:coverage.path},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals76.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals76.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals76.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals76.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals76.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals76.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals76.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals76.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
1712
+ ... (output truncated at stream read limit)`;let parsed=process.env.SWARM_LANG_BACKEND!=="legacy"?await parseTestOutputViaDispatch(framework,output,cwd)??parseTestOutput2(framework,output):parseTestOutput2(framework,output),parsedTestCases=parseFrameworkJsonTestResults(framework,output),totals={...parsed.totals},{coveragePercent}=parsed;if(totals.total===0&&parsedTestCases.length>0){for(let entry of parsedTestCases)if(entry.result==="pass")totals.passed++;else if(entry.result==="fail")totals.failed++;else totals.skipped++;totals.total=parsedTestCases.length}let isTimeout=exitCode===-1;if(exitCode===0&&totals.failed===0){let result={success:!0,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,outcome:"pass",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;if(result.message=`${framework} tests passed (${totals.passed}/${totals.total})`,coveragePercent!==void 0)result.message+=` with ${coveragePercent}% coverage`;return result}else{let result={success:!1,framework,scope,command,timeout_ms,duration_ms,totals,rawOutput:output,error:isTimeout?`Tests timed out after ${timeout_ms}ms`:`Tests failed with ${totals.failed} failures`,message:isTimeout?`${framework} tests timed out after ${timeout_ms}ms`:`${framework} tests failed (${totals.failed}/${totals.total} failed)`,outcome:isTimeout?"error":"regression",testCases:parsedTestCases};if(coveragePercent!==void 0)result.coveragePercent=coveragePercent;return result}}catch(error93){let duration_ms=Date.now()-startTime;return{success:!1,framework,scope,command,timeout_ms,duration_ms,error:error93 instanceof Error?`Execution failed: ${error93.message}`:"Execution failed: unknown error",outcome:"error"}}}function normalizeHistoryTestFile(testFile,workingDir){let normalized=testFile.replace(/\\/g,"/");if(!path112.isAbsolute(testFile))return normalized;let relative23=path112.relative(workingDir,testFile);if(relative23.startsWith("..")||path112.isAbsolute(relative23))return normalized;return relative23.replace(/\\/g,"/")}function combineAggregateResult(current,next){if(current==="fail"||next==="fail")return"fail";if(current==="pass"||next==="pass")return"pass";return"skip"}function recordAndAnalyzeResults(result,testFiles,workingDir,sourceFiles,parsedTestCases){if(!result.totals||result.totals.total===0)return;let now=new Date().toISOString(),changedFiles=(sourceFiles&&sourceFiles.length>0?sourceFiles:testFiles).map((f)=>f.replace(/\\/g,"/")),aggregateResultsByFile=new Map,validParsedCases=parsedTestCases?.filter((parsedCase)=>parsedCase.testFile.length>0&&parsedCase.testName.length>0)??[],allRecords=[];for(let parsedCase of validParsedCases){let normalizedTestFile=normalizeHistoryTestFile(parsedCase.testFile,workingDir);allRecords.push({timestamp:now,taskId:"auto",testFile:normalizedTestFile,testName:parsedCase.testName,result:parsedCase.result,durationMs:parsedCase.durationMs,errorMessage:parsedCase.errorMessage,stackPrefix:parsedCase.stackPrefix,changedFiles}),aggregateResultsByFile.set(normalizedTestFile,combineAggregateResult(aggregateResultsByFile.get(normalizedTestFile),parsedCase.result))}if(aggregateResultsByFile.size===0){let aggregateResult=result.success?"pass":"fail";for(let testFile of testFiles)aggregateResultsByFile.set(testFile.replace(/\\/g,"/"),aggregateResult)}for(let[testFile,aggregateResult]of aggregateResultsByFile)allRecords.push({timestamp:now,taskId:"auto",testFile,testName:AGGREGATE_TEST_NAME,result:aggregateResult,durationMs:result.duration_ms||0,changedFiles});try{batchAppendTestRuns(allRecords,workingDir)}catch{}}function selectHistoryForAnalysis(history){let filesWithIndividualRecords=new Set;for(let record3 of history)if(record3.testName!==AGGREGATE_TEST_NAME)filesWithIndividualRecords.add(record3.testFile.toLowerCase());if(filesWithIndividualRecords.size===0)return history;return history.filter((record3)=>record3.testName!==AGGREGATE_TEST_NAME||!filesWithIndividualRecords.has(record3.testFile.toLowerCase()))}function analyzeFailures(workingDir){let report={flakyTests:[],failureClusters:[],quarantinedFailures:[]};try{let history=selectHistoryForAnalysis(getAllHistory(workingDir));if(history.length===0)return report;report.flakyTests=detectFlakyTests(history);let failingResults=history.filter((r)=>r.result==="fail");if(failingResults.length>0){let{clusters}=classifyAndCluster(failingResults,history);report.failureClusters=clusters.map((c)=>({rootCause:c.rootCause,affectedFiles:c.affectedTestFiles,classification:c.classification}))}for(let entry of report.flakyTests)if(entry.isQuarantined)report.quarantinedFailures.push(`${entry.testFile}: ${entry.testName}`)}catch{}return report}var MAX_OUTPUT_BYTES3=512000,MAX_COMMAND_LENGTH2=500,DEFAULT_TIMEOUT_MS=60000,MAX_TIMEOUT_MS=300000,MAX_SAFE_TEST_FILES=50,MAX_SAFE_SOURCE_FILES=1,AGGREGATE_TEST_NAME="(aggregate)",VITEST_JSON_OUTPUT_RELATIVE_PATH=".swarm/cache/test-runner-vitest.json",POWERSHELL_METACHARACTERS,DISPATCH_FRAMEWORK_MAP,COMPOUND_TEST_EXTENSIONS,TEST_DIRECTORY_NAMES,SOURCE_EXTENSIONS,test_runner;var init_test_runner=__esm(()=>{init_zod();init_discovery();init_analyzer();init_failure_classifier();init_history_store();init_bun_compat();init_path_security();init_create_tool();init_resolve_working_directory();POWERSHELL_METACHARACTERS=/[|;&`$(){}[\]<>"'#*?\x00-\x1f]/;DISPATCH_FRAMEWORK_MAP={bun:"bun",vitest:"vitest",jest:"jest",mocha:"mocha",pytest:"pytest",cargo:"cargo",pester:"pester","go-test":"go-test",maven:"maven",gradle:"gradle","dotnet-test":"dotnet-test",ctest:"ctest","swift-test":"swift-test","dart-test":"dart-test",rspec:"rspec",minitest:"minitest",pest:"pest",phpunit:"phpunit","php-artisan":"php-artisan","bun:test":"bun","xcodebuild-test":"swift-test","flutter test":"dart-test","dart test":"dart-test",Pest:"pest",PHPUnit:"phpunit"};COMPOUND_TEST_EXTENSIONS=[".test.ts",".test.tsx",".test.js",".test.jsx",".tests.ps1",".spec.ts",".spec.tsx",".spec.js",".spec.jsx",".test.ps1",".spec.ps1"],TEST_DIRECTORY_NAMES=["__tests__","tests","test","spec"];SOURCE_EXTENSIONS=new Set([".ts",".tsx",".js",".jsx",".mjs",".cjs",".py",".rs",".ps1",".psm1",".go",".java",".kt",".kts",".cs",".c",".h",".cpp",".hpp",".cc",".cxx",".php",".swift",".dart",".rb",".pyi"]);test_runner=createSwarmTool({description:'Run project tests with framework detection. Supports bun, vitest, jest, mocha, pytest, cargo, pester, go-test, maven, gradle, dotnet-test, ctest, swift-test, dart-test, rspec, and minitest. Returns deterministic normalized JSON with framework, scope, command, totals, coverage, duration, success status, and failures. Use scope "all" for full suite, "convention" to accept direct test files or map source files to test files, "graph" to find related tests via imports from source files, or "impact" to find tests covering changed source files using test-impact analysis.',args:{scope:exports_external.enum(["all","convention","graph","impact"]).optional().describe('Test scope: "all" runs full suite, "convention" accepts direct test files or maps source files to tests by naming, "graph" finds related tests via imports from source files, "impact" finds tests covering changed source files via test-impact analysis'),files:exports_external.array(exports_external.string()).optional().describe('Specific files to test. For "convention", pass source files or direct test files. For "graph" and "impact", pass source files only.'),coverage:exports_external.boolean().optional().describe("Enable coverage reporting if supported"),bail:exports_external.boolean().optional().describe("Stop running tests after the first failure. Default false. Note: coverage may be incomplete when bail=true with coverage=true."),timeout_ms:exports_external.number().optional().describe("Timeout in milliseconds (default 60000, max 300000)"),working_directory:exports_external.string().optional().describe("Explicit project root directory. When provided, tests run relative to this path instead of the plugin context directory. Use this when CWD differs from the actual project root.")},async execute(args2,directory){let workingDirInput;if(args2&&typeof args2==="object"){let obj=args2;workingDirInput=typeof obj.working_directory==="string"?obj.working_directory:void 0}let dirResult=resolveWorkingDirectory(workingDirInput,directory);if(!dirResult.success){let errorResult={success:!1,framework:"none",scope:"all",error:dirResult.message,outcome:"error"};return JSON.stringify(errorResult,null,2)}let workingDir=dirResult.directory;if(workingDir.length>4096)return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(/^[/\\]{2}/.test(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsControlChars(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(containsPathTraversal(workingDir))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid working directory",outcome:"error"},null,2);if(!validateArgs2(args2))return JSON.stringify({success:!1,framework:"none",scope:"all",error:"Invalid arguments",message:'scope must be "all", "convention", "graph", or "impact"; files must be array of strings; coverage must be boolean; timeout_ms must be a positive number',outcome:"error"},null,2);let scope=args2.scope||"all";if(scope==="all"){if(!process.env.SWARM_ALLOW_FULL_SUITE)return JSON.stringify({success:!1,framework:"none",scope:"all",error:'scope "all" is blocked for agent use. Use scope "convention" with specific test files, or scope "graph" with exactly one source file.',message:'The full test suite is blocked in agent context. Use scope "convention" with specific test files, or scope "graph" with exactly one source file. Example: { scope: "convention", files: ["src/tools/test-runner.ts"] }',outcome:"error"},null,2)}if((scope==="convention"||scope==="graph"||scope==="impact")&&(!args2.files||args2.files.length===0))return JSON.stringify({success:!1,framework:"none",scope,error:'scope "convention" and "graph" require explicit files array - omitting files causes unsafe full-project discovery',message:'When using scope "convention" or "graph", you must provide a non-empty "files" array. Use scope "all" for full project test suite without specifying files.',outcome:"error"},null,2);let _files=args2.files||[],coverage=args2.coverage||!1,bail=args2.bail||!1,timeout_ms=Math.min(args2.timeout_ms||DEFAULT_TIMEOUT_MS,MAX_TIMEOUT_MS),useDispatch=process.env.SWARM_LANG_BACKEND!=="legacy",framework;if(useDispatch){if(framework=await detectTestFrameworkViaDispatch(workingDir),framework==="none")framework=await detectTestFramework(workingDir)}else framework=await detectTestFramework(workingDir);if(framework==="none")return JSON.stringify({success:!1,framework:"none",scope,error:"No test framework detected",message:"No supported test framework found. Install bun, vitest, jest, mocha, pytest, cargo, pester, or a supported language test runner (go test, maven, gradle, dotnet test, ctest, swift test, dart test, rspec, minitest).",totals:{passed:0,failed:0,skipped:0,total:0},outcome:"error"},null,2);let testFiles=[],graphFallbackReason,effectiveScope=scope;if(scope==="all");else if(scope==="convention"){let directTestFiles=args2.files.filter((file3)=>isConventionTestFilePath(file3)),sourceFiles=args2.files.filter((file3)=>{if(directTestFiles.includes(file3))return!1;let ext=path112.extname(file3).toLowerCase();return SOURCE_EXTENSIONS.has(ext)}),invalidFiles=args2.files.filter((file3)=>!directTestFiles.includes(file3)&&!sourceFiles.includes(file3));if(directTestFiles.length===0&&sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no recognized source files or direct test files",message:"The files array must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.) or a direct test file in a supported test location/naming convention.",outcome:"error"},null,2);if(invalidFiles.length>0){let errorResult={success:!1,framework,scope,error:"Provided files include entries that are neither recognized source files nor direct test files",message:`These files are not valid for targeted test discovery: ${invalidFiles.join(", ")}`,outcome:"error"};return JSON.stringify(errorResult,null,2)}if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "convention" accepts at most ${MAX_SAFE_SOURCE_FILES} source file for discovery (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "convention" discovery (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or pass direct test file paths instead of source files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}testFiles=[...directTestFiles,...getTestFilesFromConvention(sourceFiles,workingDir)].filter((file3,index,items)=>items.indexOf(file3)===index)}else if(scope==="graph"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path112.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "graph" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "graph" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "graph" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "graph" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}else if(scope==="impact"){let sourceFiles=args2.files.filter((f)=>{if(isConventionTestFilePath(f))return!1;let ext=path112.extname(f).toLowerCase();return SOURCE_EXTENSIONS.has(ext)});if(sourceFiles.length===0)return JSON.stringify({success:!1,framework,scope,error:"Provided files contain no source files with recognized extensions",message:'The files array for scope "impact" must contain at least one source file with a recognized extension (.ts, .tsx, .js, .jsx, .py, .rs, .ps1, etc.). Direct test files belong in scope "convention".',outcome:"error"},null,2);if(sourceFiles.length>MAX_SAFE_SOURCE_FILES){let errorResult={success:!1,framework,scope,error:`scope "impact" accepts at most ${MAX_SAFE_SOURCE_FILES} source file (got ${sourceFiles.length}). Treat this as SKIP without retry.`,message:`Too many source files for scope "impact" (${sourceFiles.length} provided, limit is ${MAX_SAFE_SOURCE_FILES}). Call test_runner once per source file, or use scope "convention" with direct test file paths.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let estimate=await estimateFanOut(sourceFiles,workingDir);if(estimate.estimatedCount>MAX_SAFE_TEST_FILES){let errorResult={success:!1,framework,scope,error:"Estimated test file count exceeds safe maximum",message:`Scope "impact" resolution would produce approximately ${estimate.estimatedCount} test files, which exceeds the safe limit of ${MAX_SAFE_TEST_FILES}. Break the source files into smaller batches and retry.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}try{let impactResult=await analyzeImpact(sourceFiles,workingDir,MAX_SAFE_TEST_FILES);if(impactResult.budgetExceeded){let errorResult={success:!1,framework,scope,error:"Budget exceeded during impact analysis",message:`Impact analysis exceeded safe budget of ${MAX_SAFE_TEST_FILES} test files.`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}if(impactResult.impactedTests.length>0)testFiles=impactResult.impactedTests.map((absPath)=>{let relativePath=path112.relative(workingDir,absPath);return path112.isAbsolute(relativePath)?absPath:relativePath});else{graphFallbackReason="no impacted tests found via impact analysis, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}catch{graphFallbackReason="impact analysis failed, falling back to graph",effectiveScope="graph";let graphTestFiles=await getTestFilesFromGraph(sourceFiles,workingDir);if(graphTestFiles.length>0)testFiles=graphTestFiles;else graphFallbackReason="imports resolution returned no results, falling back to convention",effectiveScope="convention",testFiles=getTestFilesFromConvention(sourceFiles,workingDir)}}if(scope!=="all"&&testFiles.length===0){let errorResult={success:!1,framework,scope:effectiveScope,error:"Provided source files resolved to zero test files",message:graphFallbackReason?`No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/). (${graphFallbackReason})`:"No matching test files found for the provided source files. Check that test files exist with matching naming conventions (.spec.*, .test.*, .Tests.ps1, __tests__/, tests/, test/, spec/).",outcome:"skip",...scope==="graph"&&{attempted_scope:"graph"},...scope==="impact"&&{attempted_scope:"graph"}};return JSON.stringify(errorResult,null,2)}if(scope!=="all"&&testFiles.length>MAX_SAFE_TEST_FILES){let sampleFiles=testFiles.slice(0,5),errorResult={success:!1,framework,scope:effectiveScope,error:`Resolved test file count (${testFiles.length}) exceeds safe maximum (${MAX_SAFE_TEST_FILES})`,message:`Too many test files resolved (${testFiles.length}). Maximum allowed is ${MAX_SAFE_TEST_FILES}. Treat this as SKIP without retry. Provide more specific source files to narrow down test scope. First few resolved: ${sampleFiles.join(", ")}`,outcome:"scope_exceeded"};return JSON.stringify(errorResult,null,2)}let result=await runTests(framework,effectiveScope,testFiles,coverage,timeout_ms,workingDir,bail);recordAndAnalyzeResults(result,testFiles,workingDir,_files.length>0?_files:void 0,result.testCases);let historyReport;if(!result.success&&result.totals&&result.totals.failed>0){if(historyReport=analyzeFailures(workingDir),historyReport.quarantinedFailures.length>0)result.message=(result.message||"")+` | QUARANTINED (flaky): ${historyReport.quarantinedFailures.join(", ")}`;if(historyReport.failureClusters.length>0){let clusterSummary=historyReport.failureClusters.slice(0,3).map((c)=>`${c.classification}: ${c.rootCause.substring(0,80)}`).join("; ");result.message=`${result.message||""} | FAILURE ANALYSIS: ${clusterSummary}`}}if(graphFallbackReason&&result.message)result.message=`${result.message} (${graphFallbackReason})`;if(bail&&coverage&&result.message)result.message=`${result.message} (coverage may be incomplete: bail=true stopped early)`;return JSON.stringify(result,null,2)}})});import*as fs57 from"node:fs";import*as path113 from"node:path";function validateDirectoryPath(dir){if(!dir||typeof dir!=="string")throw Error("Directory path is required");if(dir.includes(".."))throw Error("Directory path must not contain path traversal sequences");let normalized=path113.normalize(dir);return path113.isAbsolute(normalized)?normalized:path113.resolve(normalized)}function validateTimeout(timeoutMs,defaultValue){if(timeoutMs===void 0)return defaultValue;if(typeof timeoutMs!=="number"||!Number.isFinite(timeoutMs))throw Error("Timeout must be a finite number");if(timeoutMs<=0)throw Error("Timeout must be greater than 0");if(timeoutMs<MIN_CHECK_TIMEOUT_MS)throw Error(`Timeout must be at least ${MIN_CHECK_TIMEOUT_MS}ms (5 seconds)`);if(timeoutMs>MAX_CHECK_TIMEOUT_MS)throw Error(`Timeout must not exceed ${MAX_CHECK_TIMEOUT_MS}ms (5 minutes)`);return timeoutMs}function getPackageVersion(dir){try{let packagePath=path113.join(dir,"package.json");if(fs57.existsSync(packagePath)){let content=fs57.readFileSync(packagePath,"utf-8");return JSON.parse(content).version??null}}catch{}return null}function getChangelogVersion(dir){try{let changelogPath=path113.join(dir,"CHANGELOG.md");if(fs57.existsSync(changelogPath)){let match=fs57.readFileSync(changelogPath,"utf-8").match(/^##\s*\[?(\d+\.\d+\.\d+)\]?/m);if(match)return match[1]}}catch{}return null}function getVersionFileVersion(dir){let possibleFiles=["VERSION.txt","version.txt","VERSION","version"];for(let file3 of possibleFiles){let filePath=path113.join(dir,file3);if(fs57.existsSync(filePath))try{let match=fs57.readFileSync(filePath,"utf-8").trim().match(/(\d+\.\d+\.\d+)/);if(match)return match[1]}catch{}}return null}async function runVersionCheck2(dir,_timeoutMs){let startTime=Date.now();try{let packageVersion=_internals76.getPackageVersion(dir),changelogVersion=_internals76.getChangelogVersion(dir),versionFileVersion=_internals76.getVersionFileVersion(dir),versions3=[];if(packageVersion)versions3.push(`package.json: ${packageVersion}`);if(changelogVersion)versions3.push(`CHANGELOG.md: ${changelogVersion}`);if(versionFileVersion)versions3.push(`version file: ${versionFileVersion}`);if(new Set([packageVersion,changelogVersion,versionFileVersion].filter(Boolean)).size<=1){if(versions3.length===0)return{type:"version",status:"skip",message:"No version information found to check",details:{},durationMs:Date.now()-startTime};return{type:"version",status:"pass",message:`Version consistent: ${versions3.join(", ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}return{type:"version",status:"fail",message:`Version mismatch: ${versions3.join("; ")}`,details:{packageVersion,changelogVersion,versionFileVersion},durationMs:Date.now()-startTime}}catch(error93){return{type:"version",status:"error",message:`Version check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runLintCheck(dir,linter,timeoutMs){let startTime=Date.now();try{let lintPromise=runLint(linter,"check",dir),timeoutId,timeoutPromise=new Promise((_,reject)=>{timeoutId=setTimeout(()=>{reject(Error(`Lint check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([lintPromise,timeoutPromise]).finally(()=>clearTimeout(timeoutId));if(!result.success)return{type:"lint",status:"error",message:result.error??"Lint check failed",details:{linter,success:result.success},durationMs:Date.now()-startTime};if(result.exitCode!==0){let issueMatch=result.output.match(/(\d+)\s+(issues?|errors?)/i),issueCount=issueMatch?parseInt(issueMatch[1],10):void 0;return{type:"lint",status:"fail",message:issueCount?`Lint found ${issueCount} issue(s)`:"Lint found issues",details:{linter,exitCode:result.exitCode,issueCount,hasOutput:result.output.length>0},durationMs:Date.now()-startTime}}return{type:"lint",status:"pass",message:"Lint check passed",details:{linter,exitCode:result.exitCode},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))return{type:"lint",status:"error",message:error93.message,details:{linter},durationMs:Date.now()-startTime};return{type:"lint",status:"error",message:`Lint check failed: ${error93 instanceof Error?error93.message:String(error93)}`,details:{linter},durationMs:Date.now()-startTime}}}async function runTestsCheck(_dir,scope,timeoutMs){let startTime=Date.now();try{let result=await runTests("none",scope,[],!1,timeoutMs,_dir,!1);if(!result.success)return{type:"tests",status:"error",message:result.error??"Tests check failed",details:{framework:result.framework,scope,success:result.success},durationMs:Date.now()-startTime};if(result.totals.failed>0)return{type:"tests",status:"fail",message:`Tests failed: ${result.totals.failed}/${result.totals.total} failed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime};if(result.totals.total===0)return{type:"tests",status:"skip",message:"No tests found to run",details:{framework:result.framework,scope},durationMs:Date.now()-startTime};return{type:"tests",status:"pass",message:`Tests passed: ${result.totals.passed} passed`,details:{framework:result.framework,scope,totals:result.totals},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&(error93.message.includes("timeout")||error93.message.includes("ETIMEDOUT")))return{type:"tests",status:"error",message:`Tests check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"tests",status:"error",message:`Tests check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runSecretsCheck(dir,timeoutMs){let startTime=Date.now();try{let secretsPromise=runSecretscan(dir),timeoutPromise=new Promise((_,reject)=>{setTimeout(()=>{reject(Error(`Secrets check timed out after ${timeoutMs}ms`))},timeoutMs)}),result=await Promise.race([secretsPromise,timeoutPromise]);if(result.findings&&result.findings.length>0){let critical=result.findings.filter((f)=>f.severity==="critical").length,high=result.findings.filter((f)=>f.severity==="high").length;return{type:"secrets",status:"fail",message:`Found ${result.findings.length} secret(s): ${critical} critical, ${high} high`,details:{count:result.count,critical,high,filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}return{type:"secrets",status:"pass",message:"No secrets detected",details:{filesScanned:result.files_scanned},durationMs:Date.now()-startTime}}catch(error93){if(error93 instanceof Error&&error93.name==="AbortError")return{type:"secrets",status:"error",message:`Secrets check timed out after ${timeoutMs}ms`,durationMs:Date.now()-startTime};return{type:"secrets",status:"error",message:`Secrets check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runEvidenceCheck(dir){let startTime=Date.now();try{let plan=await loadPlan(dir);if(!plan)return{type:"evidence",status:"skip",message:"No plan found to check evidence against",details:{},durationMs:Date.now()-startTime};let completedTaskIds=[];for(let phase of plan.phases)for(let task of phase.tasks)if(task.status==="completed")completedTaskIds.push(task.id);if(completedTaskIds.length===0)return{type:"evidence",status:"skip",message:"No completed tasks yet",details:{completedTasks:0},durationMs:Date.now()-startTime};let evidenceTaskIds=new Set(await listEvidenceTaskIds(dir)),missingEvidence=[];for(let id of completedTaskIds){let gateStatus=await getDurableGateEvidenceStatusForTask(dir,id);if(gateStatus.isComplete)continue;if(gateStatus.evidenceExists&&gateStatus.missingGates.length>0){missingEvidence.push(id);continue}if(evidenceTaskIds.has(id))continue;missingEvidence.push(id)}let completedWithEvidence=completedTaskIds.length-missingEvidence.length;if(missingEvidence.length>0)return{type:"evidence",status:"fail",message:`${missingEvidence.length} completed task(s) missing evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence,missingTasks:missingEvidence.slice(0,10),missingCount:missingEvidence.length},durationMs:Date.now()-startTime};return{type:"evidence",status:"pass",message:`All ${completedTaskIds.length} completed tasks have evidence`,details:{totalCompleted:completedTaskIds.length,totalWithEvidence:completedWithEvidence},durationMs:Date.now()-startTime}}catch(error93){return{type:"evidence",status:"error",message:`Evidence check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runRequirementCoverageCheck(dir,currentPhase){let startTime=Date.now();try{if(readEffectiveSpecSync(dir)===null)return{type:"req_coverage",status:"skip",message:"No effective spec found, requirement coverage not required",details:{},durationMs:Date.now()-startTime};let coverage=await checkRequirementCoverage(currentPhase,dir);if(coverage.exists)return{type:"req_coverage",status:"pass",message:"Requirement coverage report found",details:{path:coverage.path},durationMs:Date.now()-startTime};return{type:"req_coverage",status:"fail",message:"Requirement coverage report missing but effective spec exists",details:{expectedPath:coverage.path},durationMs:Date.now()-startTime}}catch(error93){return{type:"req_coverage",status:"error",message:`Requirement coverage check failed: ${error93 instanceof Error?error93.message:String(error93)}`,durationMs:Date.now()-startTime}}}async function runPreflight(dir,phase,config3){let startTime=Date.now(),reportId=`preflight-${Date.now()}-${Math.random().toString(36).slice(2,8)}`,validatedDir;try{validatedDir=_internals76.validateDirectoryPath(dir)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid directory: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid directory"}}let validatedTimeout;try{validatedTimeout=_internals76.validateTimeout(config3?.checkTimeoutMs,DEFAULT_CONFIG.checkTimeoutMs)}catch(error93){return{id:reportId,timestamp:startTime,phase,overall:"fail",checks:[{type:"lint",status:"error",message:`Invalid config: ${error93 instanceof Error?error93.message:String(error93)}`}],totalDurationMs:Date.now()-startTime,message:"Preflight aborted: invalid configuration"}}let cfg={checkTimeoutMs:validatedTimeout,skipTests:config3?.skipTests??DEFAULT_CONFIG.skipTests,skipSecrets:config3?.skipSecrets??DEFAULT_CONFIG.skipSecrets,skipEvidence:config3?.skipEvidence??DEFAULT_CONFIG.skipEvidence,skipVersion:config3?.skipVersion??DEFAULT_CONFIG.skipVersion,testScope:config3?.testScope??DEFAULT_CONFIG.testScope,linter:config3?.linter??DEFAULT_CONFIG.linter};log("[Preflight] Starting preflight checks",{reportId,phase,config:{skipTests:cfg.skipTests,skipSecrets:cfg.skipSecrets,skipEvidence:cfg.skipEvidence,skipVersion:cfg.skipVersion,testScope:cfg.testScope,linter:cfg.linter}});let checks5=[];log("[Preflight] Running lint check...");let lintResult=await _internals76.runLintCheck(validatedDir,cfg.linter,cfg.checkTimeoutMs);if(checks5.push(lintResult),log(`[Preflight] Lint check: ${lintResult.status} ${lintResult.message}`),!cfg.skipTests){log("[Preflight] Running tests check...");let testsResult=await _internals76.runTestsCheck(validatedDir,cfg.testScope,cfg.checkTimeoutMs);checks5.push(testsResult),log(`[Preflight] Tests check: ${testsResult.status} ${testsResult.message}`)}else checks5.push({type:"tests",status:"skip",message:"Tests check skipped by configuration"});if(!cfg.skipSecrets){log("[Preflight] Running secrets check...");let secretsResult=await _internals76.runSecretsCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(secretsResult),log(`[Preflight] Secrets check: ${secretsResult.status} ${secretsResult.message}`)}else checks5.push({type:"secrets",status:"skip",message:"Secrets check skipped by configuration"});if(!cfg.skipEvidence){log("[Preflight] Running evidence check...");let evidenceResult=await _internals76.runEvidenceCheck(validatedDir);checks5.push(evidenceResult),log(`[Preflight] Evidence check: ${evidenceResult.status} ${evidenceResult.message}`)}else checks5.push({type:"evidence",status:"skip",message:"Evidence check skipped by configuration"});log("[Preflight] Running requirement coverage check...");let reqCoverageResult=await _internals76.runRequirementCoverageCheck(validatedDir,phase);if(checks5.push(reqCoverageResult),log(`[Preflight] Requirement coverage check: ${reqCoverageResult.status} ${reqCoverageResult.message}`),!cfg.skipVersion){log("[Preflight] Running version check...");let versionResult=await _internals76.runVersionCheck(validatedDir,cfg.checkTimeoutMs);checks5.push(versionResult),log(`[Preflight] Version check: ${versionResult.status} ${versionResult.message}`)}else checks5.push({type:"version",status:"skip",message:"Version check skipped by configuration"});let totalDurationMs=Date.now()-startTime,failedChecks=checks5.filter((c)=>c.status==="fail").length,errorChecks=checks5.filter((c)=>c.status==="error").length,skippedChecks=checks5.filter((c)=>c.status==="skip").length,overall,message;if(errorChecks>0)overall="fail",message=`Preflight failed with ${errorChecks} error(s)`;else if(failedChecks>0)overall="fail",message=`Preflight failed: ${failedChecks} check(s) failed`;else if(skippedChecks===checks5.length)overall="skipped",message="All checks were skipped";else overall="pass",message="Preflight passed all checks";return log(`[Preflight] Complete: ${overall} ${message}`),{id:reportId,timestamp:startTime,phase,overall,checks:checks5,totalDurationMs,message}}function formatPreflightMarkdown(report){let lines=["## Preflight Report","",`**Phase**: ${report.phase}`,`**Overall**: ${report.overall==="pass"?"✅ PASS":report.overall==="fail"?"❌ FAIL":"⏭️ SKIPPED"}`,`**Duration**: ${(report.totalDurationMs/1000).toFixed(2)}s`,"","### Checks",""];for(let check3 of report.checks){let icon=check3.status==="pass"?"✅":check3.status==="fail"?"❌":check3.status==="error"?"⚠️":"⏭️";lines.push(`- ${icon} **${check3.type}**: ${check3.message}`)}return lines.push(""),lines.push(report.message),lines.join(`
1713
1713
  `)}async function handlePreflightCommand(directory,_args){let phase=(await loadPlan(directory))?.current_phase??1,report=await _internals76.runPreflight(directory,phase);return _internals76.formatPreflightMarkdown(report)}var MIN_CHECK_TIMEOUT_MS=5000,MAX_CHECK_TIMEOUT_MS=300000,DEFAULT_CONFIG,_internals76;var init_preflight_service=__esm(()=>{init_gate_bridge();init_manager2();init_manager();init_effective_spec();init_lint();init_secretscan();init_test_runner();init_utils();DEFAULT_CONFIG={checkTimeoutMs:60000,skipTests:!1,skipSecrets:!1,skipEvidence:!1,skipVersion:!1,testScope:"convention",linter:"biome"};_internals76={runPreflight,formatPreflightMarkdown,handlePreflightCommand,validateDirectoryPath,validateTimeout,getPackageVersion,getChangelogVersion,getVersionFileVersion,runVersionCheck:runVersionCheck2,runLintCheck,runTestsCheck,runSecretsCheck,runEvidenceCheck,runRequirementCoverageCheck}});var init_preflight=__esm(()=>{init_preflight_service()});async function handlePromoteCommand(directory,args2){let category,lessonId,lessonText;for(let i=0;i<args2.length;i++){let arg=args2[i];if(arg==="--category"&&i+1<args2.length)category=args2[i+1],i++;else if(arg==="--from-swarm"&&i+1<args2.length)lessonId=args2[i+1],i++;else if(!arg.startsWith("--")){lessonText=args2.slice(i).join(" ");break}}if(!lessonText&&!lessonId)return'Usage: /swarm promote "<lesson text>" or /swarm promote --from-swarm <id>';if(lessonId)try{return await promoteFromSwarm(directory,lessonId)}catch(error93){if(error93 instanceof Error)return error93.message;return`Failed to promote lesson: ${error93 instanceof Error?error93.message:String(error93)}`}try{return await promoteToHive(directory,lessonText,category)}catch(error93){if(error93 instanceof Error)return error93.message;return`Failed to promote lesson: ${error93 instanceof Error?error93.message:String(error93)}`}}var init_promote=__esm(()=>{init_hive_promoter()});function isGateName(name){return ALL_GATE_NAMES.includes(name)}function formatGates(gates){return ALL_GATE_NAMES.map((g)=>` - ${g}: ${gates[g]?"on":"off"}`).join(`
1714
1714
  `)}async function handleQaGatesCommand(directory,args2,sessionID){let plan=await loadPlanJsonOnly(directory);if(!plan)return"Error: plan.json not found or invalid. Create a plan first (e.g. /swarm specify or save_plan).";let planId=derivePlanId(plan),subcommand=args2[0]?.toLowerCase(),gateArgs=args2.slice(1);if(!subcommand||subcommand==="show"||subcommand==="status"){let profile=getProfile(directory,planId),spec=profile?profile.gates:DEFAULT_QA_GATES,overrides=(sessionID?getAgentSession(sessionID):null)?.qaGateSessionOverrides??{},effective=profile?getEffectiveGates(profile,overrides):{...DEFAULT_QA_GATES,...overrides},lines=[];if(lines.push(`QA Gate Profile for plan_id=${planId}`),!profile)lines.push(" (no profile persisted yet — showing defaults)");else lines.push(` locked: ${profile.locked_at?`yes @ ${profile.locked_at} (seq ${profile.locked_by_snapshot_seq??"?"})`:"no"}`),lines.push(` profile_hash: ${computeProfileHash(profile)}`);if(lines.push("Spec-level gates:"),lines.push(formatGates(spec)),lines.push("Session overrides (ratchet-tighter only):"),Object.keys(overrides).length===0)lines.push(" (none)");else for(let k of ALL_GATE_NAMES)if(overrides[k]===!0)lines.push(` - ${k}: on (override)`);return lines.push("Effective gates:"),lines.push(formatGates(effective)),lines.join(`
1715
1715
  `)}if(subcommand==="enable"){if(gateArgs.length===0)return"Usage: /swarm qa-gates enable <gate> [<gate> ...]";let invalid=gateArgs.filter((g)=>!isGateName(g));if(invalid.length>0)return`Error: unknown gate(s): ${invalid.join(", ")}. Valid gates: ${ALL_GATE_NAMES.join(", ")}`;getOrCreateProfile(directory,planId);let patch={};for(let g of gateArgs)if(isGateName(g))patch[g]=!0;try{let updated=setGates(directory,planId,patch);return[`Enabled gates persisted for plan_id=${planId}:`,formatGates(updated.gates),`profile_hash: ${computeProfileHash(updated)}`].join(`
@@ -1849,10 +1849,10 @@ INSTRUCTIONS: Retain ONLY the system prompt, the current task context, and the l
1849
1849
  [/CONTEXT COMPACTION]`}function createCompactionService(config3,directory,injectMessage){return{toolAfter:async(_input,_output)=>{if(!config3.enabled)return;let budgetPct=swarmState.lastBudgetPct??0;if(budgetPct<=0)return;let sessionId=_input.sessionID,state=getSessionState(sessionId);try{if(budgetPct>=config3.emergencyThreshold&&budgetPct>state.lastEmergencyAt+5){state.lastEmergencyAt=budgetPct,state.emergencyCount++;let msg=buildEmergencyMessage(budgetPct,config3.preserveLastNTurns);appendSnapshot(directory,"emergency",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.reflectionThreshold&&budgetPct>state.lastReflectionAt+5){state.lastReflectionAt=budgetPct,state.reflectionCount++;let msg=buildReflectionMessage(budgetPct);appendSnapshot(directory,"reflection",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg);return}if(budgetPct>=config3.observationThreshold&&budgetPct>state.lastObservationAt+5){state.lastObservationAt=budgetPct,state.observationCount++;let msg=buildObservationMessage(budgetPct);appendSnapshot(directory,"observation",budgetPct,msg),state.lastSnapshotAt=new Date().toISOString(),injectMessage(sessionId,msg)}}catch{}}}}function getCompactionMetrics(sessionId){if(sessionId){let state=getSessionState(sessionId);return{compactionCount:state.observationCount+state.reflectionCount+state.emergencyCount,lastSnapshotAt:state.lastSnapshotAt}}let total=0,lastSnapshot=null;for(let state of sessionStates.values())if(total+=state.observationCount+state.reflectionCount+state.emergencyCount,state.lastSnapshotAt&&(!lastSnapshot||state.lastSnapshotAt>lastSnapshot))lastSnapshot=state.lastSnapshotAt;return{compactionCount:total,lastSnapshotAt:lastSnapshot}}var sessionStates;var init_compaction_service=__esm(()=>{init_state2();sessionStates=new Map});async function readFileOrEmpty(filePath){for(let attempt=0;attempt<5;attempt++)try{return await readCachedTextFile(filePath,async()=>bunFile(filePath).text())??""}catch(err){if(err?.code!=="ENOENT"||attempt===4)return"";await new Promise((resolve48)=>setTimeout(resolve48,10))}return""}function estimateTokens2(text){if(!text||typeof text!=="string")return 0;return Math.ceil(text.length/3.5)}async function readBudgetState(directory){let content=await readSwarmFileAsync(directory,"session/budget-state.json");if(!content)return null;try{return JSON.parse(content)}catch{return null}}async function writeBudgetState(directory,state){try{let resolvedPath=validateSwarmPath(directory,"session/budget-state.json"),content=JSON.stringify(state,null,2);await bunWrite(resolvedPath,content)}catch(error93){console.warn("[context-budget] Failed to write budget state:",error93 instanceof Error?error93.message:String(error93))}}async function countEvents(directory){let content=await readSwarmFileAsync(directory,"events.jsonl");if(!content)return 0;return content.split(`
1850
1850
  `).filter((line)=>line.trim().length>0).length}async function getPlanCursorContent(directory){let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent)return"";let lines=planContent.split(`
1851
1851
  `),cursorLines=[],inCurrentSection=!1;for(let line of lines){if(line.includes("in_progress")||line.includes("**Current**"))inCurrentSection=!0;if(inCurrentSection){if(cursorLines.push(line),cursorLines.length>30)break}}return cursorLines.join(`
1852
- `)||planContent.substring(0,1000)}async function getContextBudgetReport(directory,assembledSystemPrompt,config3){validateDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status,recommendation=null;if(budgetPct<config3.warningPct)status="ok";else if(budgetPct<config3.criticalPct)status="warning",recommendation="Consider wrapping up current phase and running /swarm handoff before starting new work.";else status="critical",recommendation="Run /swarm handoff and start a new session to avoid cost escalation.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateDirectory(directory),report.status==="ok")return null;if(!directory||directory.trim()==="")return formatWarningMessage(report);let state=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state.warningFiredAtTurn!==null&&currentTurn-state.warningFiredAtTurn<config3.warningIntervalTurns)return null;state.warningFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state)}else if(report.status==="critical")state.criticalFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[CONTEXT BUDGET: ${budgetPctStr}% — swarm injecting ~${tokensPerTurn} tokens/turn. Consider wrapping current phase and running /swarm handoff before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[CONTEXT BUDGET: ${budgetPctStr}% CRITICAL — swarm injecting ~${tokensPerTurn} tokens/turn. Run /swarm handoff and start a new session to avoid cost escalation. Estimated session cost scaling: ~$${costPerTurn}/turn at current context size.]`}var DEFAULT_CONTEXT_BUDGET_CONFIG,COST_PER_1K_TOKENS=0.003;var init_context_budget_service=__esm(()=>{init_knowledge_store();init_utils2();init_bun_compat();init_path_security();init_swarm_artifact_cache();DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:40000,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20}});import*as fsSync9 from"node:fs";import{readFile as readFile27}from"node:fs/promises";import*as path123 from"node:path";function readSpecStalenessSnapshot(directory){try{let p=path123.join(directory,".swarm","spec-staleness.json");if(!fsSync9.existsSync(p))return{stale:!1};let raw=fsSync9.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}async function getStatusData(directory,agents){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task of phase.tasks)if(totalTasks++,task.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;return status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl")),enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals80.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";if(status.turboStrategy=turboStrategy,!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals80.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status.fullAutoActive=_internals80.hasActiveFullAuto(),status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off"){if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");if(status.fullAutoActive)lines.push("**Full-Auto**: active")}else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=DEFAULT_CONTEXT_BUDGET_CONFIG.budgetTokens,est=Math.round(status.contextBudgetPct/100*budgetTokens);if(lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`),status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0;if(proposals>0||unactionable>0||insights>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`)}return lines.join(`
1852
+ `)||planContent.substring(0,1000)}async function getContextBudgetReport(directory,assembledSystemPrompt,config3){validateDirectory(directory);let timestamp=new Date().toISOString(),systemPromptTokens=estimateTokens2(assembledSystemPrompt),planCursorContent=await getPlanCursorContent(directory),planCursorTokens=estimateTokens2(planCursorContent),knowledgeContent=await readFileOrEmpty(resolveSwarmKnowledgePath(directory)),knowledgeTokens=estimateTokens2(knowledgeContent),runMemoryContent=await readSwarmFileAsync(directory,"run-memory.jsonl"),runMemoryTokens=estimateTokens2(runMemoryContent||""),handoffContent=await readSwarmFileAsync(directory,"handoff.md"),handoffTokens=estimateTokens2(handoffContent||""),contextMdContent=await readSwarmFileAsync(directory,"context.md"),contextMdTokens=estimateTokens2(contextMdContent||""),swarmTotalTokens=systemPromptTokens+planCursorTokens+knowledgeTokens+runMemoryTokens+handoffTokens+contextMdTokens,estimatedTurnCount=await countEvents(directory),budgetPct=swarmTotalTokens/config3.budgetTokens*100,status,recommendation=null;if(budgetPct<config3.warningPct)status="ok";else if(budgetPct<config3.criticalPct)status="warning",recommendation="Consider wrapping up current phase and running /swarm handoff before starting new work.";else status="critical",recommendation="Run /swarm handoff and start a new session to avoid cost escalation.";let estimatedSessionTokens=swarmTotalTokens*Math.max(1,estimatedTurnCount);return{timestamp,systemPromptTokens,planCursorTokens,knowledgeTokens,runMemoryTokens,handoffTokens,contextMdTokens,swarmTotalTokens,estimatedTurnCount,estimatedSessionTokens,budgetPct,status,recommendation}}async function formatBudgetWarning(report,directory,config3){if(validateDirectory(directory),report.status==="ok")return null;if(!directory||directory.trim()==="")return formatWarningMessage(report);let state=await readBudgetState(directory)||{warningFiredAtTurn:null,criticalFiredAtTurn:null,lastInjectedAtTurn:null},currentTurn=report.estimatedTurnCount;if(report.status==="warning"){if(config3.warningMode==="once"&&state.warningFiredAtTurn!==null)return null;if(config3.warningMode==="interval"&&state.warningFiredAtTurn!==null&&currentTurn-state.warningFiredAtTurn<config3.warningIntervalTurns)return null;state.warningFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn,await writeBudgetState(directory,state)}else if(report.status==="critical")state.criticalFiredAtTurn=currentTurn,state.lastInjectedAtTurn=currentTurn;return formatWarningMessage(report)}function formatWarningMessage(report){let budgetPctStr=report.budgetPct.toFixed(1),tokensPerTurn=report.swarmTotalTokens.toLocaleString();if(report.status==="warning")return`[CONTEXT BUDGET: ${budgetPctStr}% — swarm injecting ~${tokensPerTurn} tokens/turn. Consider wrapping current phase and running /swarm handoff before starting new work.]`;let costPerTurn=(report.swarmTotalTokens/1000*COST_PER_1K_TOKENS).toFixed(3);return`[CONTEXT BUDGET: ${budgetPctStr}% CRITICAL — swarm injecting ~${tokensPerTurn} tokens/turn. Run /swarm handoff and start a new session to avoid cost escalation. Estimated session cost scaling: ~$${costPerTurn}/turn at current context size.]`}var DEFAULT_CONTEXT_BUDGET_CONFIG,COST_PER_1K_TOKENS=0.003;var init_context_budget_service=__esm(()=>{init_knowledge_store();init_utils2();init_bun_compat();init_path_security();init_swarm_artifact_cache();DEFAULT_CONTEXT_BUDGET_CONFIG={enabled:!0,budgetTokens:40000,warningPct:70,criticalPct:90,warningMode:"once",warningIntervalTurns:20}});import*as fsSync9 from"node:fs";import{readFile as readFile27}from"node:fs/promises";import*as path123 from"node:path";function readSpecStalenessSnapshot(directory){try{let p=path123.join(directory,".swarm","spec-staleness.json");if(!fsSync9.existsSync(p))return{stale:!1};let raw=fsSync9.readFileSync(p,"utf-8"),parsed=JSON.parse(raw);return{stale:!0,reason:typeof parsed?.reason==="string"?parsed.reason:void 0,storedHash:typeof parsed?.specHash_plan==="string"?parsed.specHash_plan:void 0,currentHash:typeof parsed?.specHash_current==="string"||parsed?.specHash_current===null?parsed.specHash_current:void 0}}catch{return{stale:!1}}}async function getStatusData(directory,agents){let plan=await loadPlan(directory),status;if(plan&&plan.migration_status!=="migration_failed"){let currentPhase=extractCurrentPhaseFromPlan(plan)||"Unknown",completedTasks=0,totalTasks=0;for(let phase of plan.phases)for(let task of phase.tasks)if(totalTasks++,task.status==="completed")completedTasks++;let agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!1,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let planContent=await readSwarmFileAsync(directory,"plan.md");if(!planContent){let metrics=getCompactionMetrics();status={hasPlan:!1,currentPhase:"Unknown",completedTasks:0,totalTasks:0,agentCount:Object.keys(agents).length,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}else{let currentPhase=extractCurrentPhase(planContent)||"Unknown",completedTasks=(planContent.match(/^- \[x\]/gm)||[]).length,incompleteTasks=(planContent.match(/^- \[ \]/gm)||[]).length,totalTasks=completedTasks+incompleteTasks,agentCount=Object.keys(agents).length,metrics=getCompactionMetrics();status={hasPlan:!0,currentPhase,completedTasks,totalTasks,agentCount,isLegacy:!0,turboMode:hasActiveTurboMode(),contextBudgetPct:swarmState.lastBudgetPct>0?swarmState.lastBudgetPct:null,compactionCount:metrics.compactionCount,lastSnapshotAt:metrics.lastSnapshotAt}}}let drift=readSpecStalenessSnapshot(directory);if(drift.stale)status.specStale=!0,status.specStaleReason=drift.reason,status.specStaleStoredHash=drift.storedHash,status.specStaleCurrentHash=drift.currentHash;else if(plan&&plan._specStale)status.specStale=!0,status.specStaleReason=plan._specStaleReason;if(status.recentEscalations=await readRecentEscalations(directory),status.pendingProposals=await countProposals(directory),status.unactionableQueueDepth=await safeLineCount(resolveUnactionablePath(directory)),status.insightCandidatesPending=await safeLineCount(validateSwarmPath(directory,"insight-candidates.jsonl")),status.fullAutoActive=_internals80.hasActiveFullAuto(),status.fullAutoActive){let sid=_internals80.getActiveFullAutoSessionID();if(sid){let runState=_internals80.loadFullAutoRunState(directory,sid);if(runState?.lastEscalation)status.fullAutoEscalation={reason:runState.lastEscalation.reason,interactionCount:runState.lastEscalation.interactionCount,deadlockCount:runState.lastEscalation.deadlockCount,phase:runState.lastEscalation.phase}}}return enrichWithLeanTurbo(status,directory)}function enrichWithLeanTurbo(status,directory){let turboMode=hasActiveTurboMode(),leanActive=_internals80.hasActiveLeanTurbo(),turboStrategy="off";if(leanActive)turboStrategy="lean";else if(turboMode)turboStrategy="standard";if(status.turboStrategy=turboStrategy,!leanActive)return status;let leanSessionID=null;for(let[sessionId,session]of swarmState.agentSessions)if(session.turboStrategy==="lean"&&session.leanTurboActive===!0){leanSessionID=sessionId;break}if(leanSessionID){let runState=_internals80.loadLeanTurboRunState(directory,leanSessionID);if(runState){if(status.leanTurboPhase=runState.phase,status.leanMaxParallelCoders=runState.maxParallelCoders,status.leanPauseReason=runState.pauseReason,!Array.isArray(runState.lanes))runState.lanes=[];let activeLanes=0,completedLanes=0;for(let lane of runState.lanes){if(lane.status==="running")activeLanes++;if(lane.status==="completed")completedLanes++}if(status.leanActiveLaneCount=activeLanes,status.leanCompletedLanes=completedLanes,!Array.isArray(runState.degradedTasks))runState.degradedTasks=[],status.leanDegradedTasks=0;if(runState.degradedTasks.length>0){status.leanDegradedTasks=runState.degradedTasks.length;let summaryParts=[];for(let dt of runState.degradedTasks)summaryParts.push(`${dt.taskId} (${dt.reason})`);status.leanDegradationSummary=summaryParts.join("; ")}}}return status}function formatStatusMarkdown(status){let lines=["## Swarm Status","",`**Current Phase**: ${status.currentPhase}`,`**Tasks**: ${status.completedTasks}/${status.totalTasks} complete`,`**Agents**: ${status.agentCount} registered`];if(status.specStale){let reason=status.specStaleReason??"spec.md changed since plan saved",stored=status.specStaleStoredHash??"unknown",current=status.specStaleCurrentHash??"(spec.md missing)";lines.push("",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss.")}if(status.turboStrategy&&status.turboStrategy!=="off")if(lines.push(""),status.turboStrategy==="lean"){let parts=["lean"];if(status.leanTurboPhase!==void 0)parts.push(`Phase ${status.leanTurboPhase}`);if(status.leanActiveLaneCount!==void 0){let totalLanes=(status.leanActiveLaneCount??0)+(status.leanCompletedLanes??0);parts.push(`${status.leanActiveLaneCount}/${totalLanes} lanes active`)}if(status.leanDegradedTasks!==void 0&&status.leanDegradedTasks>0)parts.push(`${status.leanDegradedTasks} degraded`);if(lines.push(`**Turbo**: ${parts.join(", ")}`),status.leanDegradationSummary)lines.push(` - ${status.leanDegradationSummary}`);if(status.leanPauseReason)lines.push(`**Lean paused**: ${status.leanPauseReason}`)}else lines.push("**Turbo**: standard");else if(status.turboStrategy===void 0&&status.turboMode===!0)lines.push(""),lines.push("**TURBO MODE**: active");if(status.fullAutoActive){if(lines.push(""),lines.push("**Full-Auto**: active"),status.fullAutoEscalation){let e=status.fullAutoEscalation,phaseStr=e.phase!==void 0?` | Phase ${e.phase}`:"";lines.push(` - Escalation: ${e.reason} (interactions=${e.interactionCount}, deadlocks=${e.deadlockCount}${phaseStr})`)}}if(status.contextBudgetPct!==null&&status.contextBudgetPct>0){let pct=status.contextBudgetPct.toFixed(1),budgetTokens=DEFAULT_CONTEXT_BUDGET_CONFIG.budgetTokens,est=Math.round(status.contextBudgetPct/100*budgetTokens);if(lines.push("",`**Context**: ${pct}% used (est. ${est.toLocaleString()} / ${budgetTokens.toLocaleString()} tokens)`),status.compactionCount>0)lines.push(`**Compaction events**: ${status.compactionCount} triggered`);if(status.lastSnapshotAt)lines.push(`**Last snapshot**: ${status.lastSnapshotAt}`)}if(status.recentEscalations&&status.recentEscalations.length>0){lines.push("","**Recently Escalated (last 7 days)**:");for(let e of status.recentEscalations)lines.push(` - ${e.entry_id} (${e.from}→${e.to}) reason=${e.reason}`)}let proposals=status.pendingProposals??0,unactionable=status.unactionableQueueDepth??0,insights=status.insightCandidatesPending??0;if(proposals>0||unactionable>0||insights>0){if(lines.push("","**Learning Queues**:"),proposals>0)lines.push(` - Pending proposals: ${proposals} (review with \`/swarm skill list\`)`);if(unactionable>0)lines.push(` - Unactionable queue: ${unactionable} (inspect with \`/swarm knowledge unactionable\`)`);if(insights>0)lines.push(` - Insight candidates: ${insights} (consumed at phase end)`)}return lines.join(`
1853
1853
  `)}async function handleStatusCommand(directory,agents){let statusData=await getStatusData(directory,agents);if(!statusData.hasPlan){if(statusData.specStale){let reason=statusData.specStaleReason??"spec.md changed since plan saved",stored=statusData.specStaleStoredHash??"unknown",current=statusData.specStaleCurrentHash??"(spec.md missing)";return["No active swarm plan found.","",`**Spec drift detected**: ${reason} (stored: ${stored}, current: ${current})`,"Run `/swarm clarify` to update the spec or `/swarm acknowledge-spec-drift` to dismiss."].join(`
1854
1854
  `)}return"No active swarm plan found."}return formatStatusMarkdown(statusData)}async function safeLineCount(filePath){try{if(!fsSync9.existsSync(filePath))return 0;let content=await readFile27(filePath,"utf-8"),n=0;for(let line of content.split(`
1855
- `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync9.existsSync(proposalsDir))return 0;let{readdir:readdir8}=await import("node:fs/promises");return(await readdir8(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals80;var init_status_service=__esm(()=>{init_extractors();init_knowledge_escalator();init_knowledge_validator();init_utils2();init_manager();init_state2();init_state4();init_compaction_service();init_context_budget_service();_internals80={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
1855
+ `))if(line.trim())n++;return n}catch{return 0}}async function countProposals(directory){try{let proposalsDir=validateSwarmPath(directory,"skills/proposals");if(!fsSync9.existsSync(proposalsDir))return 0;let{readdir:readdir8}=await import("node:fs/promises");return(await readdir8(proposalsDir)).filter((f)=>f.endsWith(".md")).length}catch{return 0}}var _internals80;var init_status_service=__esm(()=>{init_state3();init_extractors();init_knowledge_escalator();init_knowledge_validator();init_utils2();init_manager();init_state2();init_state4();init_compaction_service();init_context_budget_service();_internals80={loadLeanTurboRunState,hasActiveLeanTurbo,hasActiveFullAuto,getActiveFullAutoSessionID,loadFullAutoRunState}});var init_status=__esm(()=>{init_status_service()});async function handleSyncPlanCommand(directory,_args){let plan=await loadPlan(directory);if(!plan)return`## Plan Sync Report
1856
1856
 
1857
1857
  No active swarm plan found. Nothing to sync.`;return["## Plan Sync Report","","**Status**: ✅ Synced","","The plan.json and plan.md are now synchronized.","","### Current Plan","",derivePlanMarkdown(plan)].join(`
1858
1858
  `)}var init_sync_plan=__esm(()=>{init_manager()});async function handleTurboCommand(directory,args2,sessionID){if(!sessionID||sessionID.trim()==="")return"Error: No active session context. Turbo Mode requires an active session. Use /swarm turbo from within an OpenCode session, or start a session first.";let session=getAgentSession(sessionID);if(!session)return"Error: No active session. Turbo Mode requires an active session to operate.";let arg0=args2[0]?.toLowerCase(),arg1=args2[1]?.toLowerCase();if(arg0==="status")return buildStatusMessage2(session,directory,sessionID);let isTurboOn=session.turboMode,isLeanActive=session.leanTurboActive===!0,disableTurbo=(reason)=>{if(isLeanActive)try{pauseLeanTurboRun(directory,sessionID,reason)}catch(error93){error48(`[turbo] pauseLeanTurboRun failed: ${error93 instanceof Error?error93.message:String(error93)}`)}try{disableEpicMode(directory,sessionID)}catch(error93){error48(`[turbo] disableEpicMode (cross-clear) failed: ${error93 instanceof Error?error93.message:String(error93)}`)}session.epicModeActive=!1,session.turboMode=!1,session.turboStrategy=void 0,session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0};if(arg0==="off"||arg0==="lean"&&arg1==="off")return disableTurbo("/swarm turbo off"),"Turbo Mode disabled";if(arg0==="standard"&&arg1==="off")return disableTurbo("/swarm turbo standard off"),"Turbo Mode disabled";if(arg0===void 0)if(isTurboOn)return disableTurbo("/swarm turbo (toggle off)"),"Turbo Mode disabled";else return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled";if(arg0==="on"){let strategy="standard";try{let{config:config3}=_internals81.loadPluginConfigWithMeta(directory);if(config3.turbo?.strategy==="lean")strategy="lean"}catch(error93){warn(`[turbo] could not read config for strategy default: ${error93 instanceof Error?error93.message:String(error93)}`)}if(strategy==="lean")return enableLeanTurbo(session,directory,sessionID);if(isLeanActive)disableTurbo("/swarm turbo on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled"}if(arg0==="standard"&&arg1==="on"){if(isLeanActive)disableTurbo("/swarm turbo standard on (switching from lean)");return session.turboMode=!0,session.turboStrategy="standard",session.leanTurboActive=!1,session.leanTurboCurrentPhase=void 0,"Turbo Mode enabled (standard)"}if(arg0==="lean"&&arg1==="on")return enableLeanTurbo(session,directory,sessionID);if(arg0==="lean"&&arg1===void 0)if(isLeanActive)return disableTurbo("/swarm turbo lean (toggle off)"),"Turbo Mode disabled";else return enableLeanTurbo(session,directory,sessionID);if(arg0==="epic"&&arg1==="on"){let leanMsg=enableLeanTurbo(session,directory,sessionID);if(!session.leanTurboActive)return`${leanMsg}
@@ -1932,7 +1932,7 @@ Subcommands:
1932
1932
  `+` concurrency status — Show effective concurrency (override, plan baseline, operational effective)
1933
1933
  `+` concurrency reset — Clear the session concurrency override
1934
1934
  `+`
1935
- `+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},simulate:{handler:(ctx)=>handleSimulateCommand(ctx.directory,ctx.args),description:"Dry-run hidden coupling analysis with configurable thresholds",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},sdd:{handler:(ctx)=>handleSddCommand(ctx.directory,ctx.args),description:"Manage OpenSpec-compatible SDD artifacts and effective spec projection",args:"status|validate|project [--json] [--change <id>] [--dry-run]",details:"Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning.",category:"utility",toolPolicy:"agent"},"sdd status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",subcommandOf:"sdd",args:"[--json]",category:"utility",toolPolicy:"agent"},"sdd validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",subcommandOf:"sdd",args:"[--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",subcommandOf:"sdd",args:"[--dry-run] [--overwrite] [--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd-status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",aliasOf:"sdd status",deprecated:!0},"sdd-validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",aliasOf:"sdd validate",deprecated:!0},"sdd-project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",aliasOf:"sdd project",deprecated:!0},analyze:{handler:(ctx)=>handleAnalyzeCommand(ctx.directory,ctx.args),description:"Analyze spec.md vs plan.md for requirement coverage gaps",args:"",category:"agent",toolPolicy:"none"},clarify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleClarifyCommand),description:"Clarify and refine an existing feature specification",args:"[description-text]",category:"agent",toolPolicy:"none"},specify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleSpecifyCommand),description:"Generate or import a feature specification [description]",args:"[description-text]",category:"agent",toolPolicy:"none"},brainstorm:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleBrainstormCommand),description:"Enter architect MODE: BRAINSTORM — structured seven-phase planning workflow [topic]",args:"[topic-text]",details:"Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",category:"agent",toolPolicy:"none"},loop:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleLoopCommand),description:"Enter architect MODE: LOOP — compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [objective]",args:"<objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]",details:`Triggers the architect to run the compound-engineering loop defined in ${BUNDLED_PROJECT_SKILL_ROOT}/loop/SKILL.md: BRAINSTORM (requirements) → PLAN (+ critic gate) → BUILD (execute) → REVIEW (independent reviewer + critic on the diff, report-only) → IMPROVE (phase-wrap retrospective + compounding learning capture), then evaluate stop conditions and loop for another improvement cycle if the objective is unmet and budget remains. Generator and reviewer/critic run in separate contexts; failing assertions must be fixed at the root cause, never weakened, mocked, or skipped. Defense-in-depth stop conditions: objective met, --max-cycles budget (default 3), no-progress/plateau, oscillation, unrecoverable error, or explicit user stop. --autonomy auto (default) runs unattended with hard stops still enforced; --autonomy checkpoint pauses at phase gates for user approval. --depth exhaustive widens exploration. --resume continues an existing loop run from durable .swarm/loop/ state. Distinct from full-auto (autonomous cross-phase oversight) and turbo (parallel lanes within a phase): loop is a user-initiated, gated, compounding workflow.`,category:"agent",toolPolicy:"none"},council:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCouncilCommand),description:"Enter architect MODE: COUNCIL — multi-model deliberation [question] [--preset <name>] [--spec-review]",args:"<question> [--preset <name>] [--spec-review]",details:"Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). Use --preset <name> to choose a named member preset from council.general.presets. "+"The architect first runs 1–3 targeted web searches and passes a compiled RESEARCH CONTEXT "+"to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",category:"agent",toolPolicy:"none"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand),description:"Launch deep PR review with multi-lane analysis [url] [--council]",args:"<pr-url|owner/repo#N|N> [--council]",details:"Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, launches all 6 fixed base explorer lanes through dispatch_lanes_async while the architect keeps doing non-dependent work, polls collect_lane_results incrementally, runs every triggered micro-lane, validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, then synthesizes only after coverage is closed. If lane tools cannot close coverage, Task-tool dispatch is the final verified-equivalent fallback; if equivalence cannot be proven, the review is BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"pr-feedback":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrFeedbackCommand),description:"Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",args:"[url|owner/repo#N|N] [instructions...]",details:"Triggers MODE: PR_FEEDBACK — ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"pr subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:'Subscribes the current session to PR state-change events for the specified PR. When pr_monitor.enabled is true, the background polling worker detects CI failures, new comments, review state changes (changes requested / approved), merge conflicts and conflict resolutions, and merge/close events — each gated by its pr_monitor notify_* config flag (notify_ci_success defaults to false). Delivery follows pr_monitor.event_delivery: "prompt" (default) wakes the subscribed session with a structured <pr-activity> message; "advisory" queues session-scoped advisories with dedup tokens for the next turn. Subscriptions are idempotent, capped by pr_monitor.max_subscriptions, and agent-callable. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.',category:"agent",toolPolicy:"agent"},"pr-subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",aliasOf:"pr subscribe",deprecated:!0},"pr unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:"Unsubscribes the current session from PR state-change events for the specified PR. Removes the active subscription record (idempotent; agent-callable). Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"agent"},"pr-unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",aliasOf:"pr unsubscribe",deprecated:!0},"pr status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",args:"",details:"Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",category:"agent",toolPolicy:"agent",toolNoArgs:!0},"pr-status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",aliasOf:"pr status",deprecated:!0},"ci-simulate":{handler:(ctx)=>handleCiSimulateCommand(ctx.directory,ctx.args),description:"Create a temporary merge-result worktree and run CI before merge queue entry",args:"[--base origin/main] [--head <ref>]",details:"Creates a detached temporary worktree under .swarm/ci-simulate from the base ref, merges the current worktree HEAD (or --head ref), runs fixed local CI gates (typecheck, Biome CI, build, unit/integration/security/smoke tests, drift check), then removes the worktree and prunes metadata. Intended as a pre-queue merge_group simulation helper.",category:"agent",toolPolicy:"agent"},"deep-dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",details:"Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",category:"agent",toolPolicy:"none"},"deep dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Alias for /swarm deep-dive — launch deep codebase audit",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"deep-dive"},"deep-research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",details:"Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only — does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",category:"agent",toolPolicy:"none"},"deep research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Alias for /swarm deep-research — launch a cited deep research pass",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",category:"agent",aliasOf:"deep-research"},"codebase-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",details:"Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",category:"agent",toolPolicy:"none"},"codebase review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Alias for /swarm codebase-review - launch codebase-review-swarm",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"codebase-review"},"design-docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",args:"<description> [--out <dir>] [--lang <name>] [--update]",details:"Triggers the architect to enter MODE: DESIGN_DOCS — delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",category:"agent",toolPolicy:"none"},"design docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Alias for /swarm design-docs — generate or sync design docs",args:"<description> [--out <dir>] [--lang <name>] [--update]",category:"agent",aliasOf:"design-docs"},issue:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleIssueCommand),description:"Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",args:"<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",details:"Triggers the architect to enter MODE: ISSUE_INGEST — ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the full fix-and-PR workflow (implies --plan). --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"qa-gates":{handler:(ctx)=>handleQaGatesCommand(ctx.directory,ctx.args,ctx.sessionID),description:"View or modify QA gate profile for the current plan [enable|override <gate>...]",args:"[show|enable|override] <gate>...",details:"show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",category:"config",toolPolicy:"none"},link:{handler:(ctx)=>handleLinkCommand(ctx.directory,ctx.args),description:"Tie this worktree to a shared swarm knowledge store [name]",details:"Links the current worktree to a shared knowledge store so multiple swarms working on the same project (e.g. separate git worktrees) pool their lessons instead of each keeping an isolated .swarm/knowledge.jsonl. With no name, ties all worktrees of the same repo via the project hash; with a name, ties any worktrees/repos that use the same name. Existing local lessons are merged (deduped) into the shared store. Use `/swarm link status` to inspect.",args:"[<name> | status]",category:"utility",toolPolicy:"none"},"link status":{handler:(ctx)=>handleLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares knowledge via a link",subcommandOf:"link",category:"utility",toolPolicy:"none"},unlink:{handler:(ctx)=>handleUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing swarm knowledge for this worktree [--no-copy]",details:"Unlinks the current worktree from its shared knowledge store and returns it to a local .swarm/knowledge.jsonl. By default the shared lessons are copied back into the local store (deduped) so nothing is lost; pass --no-copy to skip the copy-back.",args:"[--no-copy]",category:"utility",toolPolicy:"none"},promote:{handler:(ctx)=>handlePromoteCommand(ctx.directory,ctx.args),description:"Manually promote lesson to hive knowledge",details:"Promotes a lesson directly to hive knowledge (--category flag sets category) or references an existing swarm lesson by ID (--from-swarm). Validates lesson text before promotion. Either direct text or --from-swarm ID is required.",args:"--category <category>, --from-swarm <lesson-id>, <lesson-text>",category:"utility",toolPolicy:"none"},reset:{handler:(ctx)=>handleResetCommand(ctx.directory,ctx.args),description:"Clear swarm state files [--confirm]",details:"DELETES plan.md, context.md, and summaries/ directory from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag — without it, displays a warning and tips to export first.",args:"--confirm (required)",category:"utility",clashesWithNativeCcCommand:"/reset",toolPolicy:"restricted"},"reset-session":{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",details:"Deletes only .swarm/session/state.json and any other session files. Clears in-memory agent sessions and delegation chains. Preserves plan, evidence, and knowledge for cross-session continuity.",args:"",category:"utility",toolPolicy:"restricted"},rollback:{handler:(ctx)=>handleRollbackCommand(ctx.directory,ctx.args),description:"Restore swarm state or project files to a checkpoint",details:"Restores legacy .swarm/ phase checkpoints from checkpoints/phase-<N> when present. Otherwise restores named git checkpoints from .swarm/checkpoints.json by label or list number. Writes rollback event to events.jsonl. Without an argument, lists available checkpoints.",args:"<phase-number|label|list-number>",category:"utility",toolPolicy:"restricted"},retrieve:{handler:(ctx)=>handleRetrieveCommand(ctx.directory,ctx.args),description:"Retrieve full output from a summary <id>",args:"<summary-id>",details:"Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",category:"utility",toolPolicy:"agent"},handoff:{handler:(ctx)=>handleHandoffCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Prepare state for clean model switch (new session)",args:"",details:"Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",category:"core",toolPolicy:"none"},turbo:{handler:(ctx)=>handleTurboCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Turbo Mode strategy for the active session [on|off|lean|standard|epic|status]",args:"on, off, lean, standard, epic, status",details:`Toggles Turbo Mode for the current session. Supports three strategies:
1935
+ `+"Session-scoped — resets on new session.",category:"utility",toolPolicy:"none"},simulate:{handler:(ctx)=>handleSimulateCommand(ctx.directory,ctx.args),description:"Dry-run hidden coupling analysis with configurable thresholds",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},sdd:{handler:(ctx)=>handleSddCommand(ctx.directory,ctx.args),description:"Manage OpenSpec-compatible SDD artifacts and effective spec projection",args:"status|validate|project [--json] [--change <id>] [--dry-run]",details:"Parent command for spec-driven development artifacts. Use sdd status to inspect .swarm/spec.md plus openspec/ artifacts, sdd validate to validate OpenSpec-compatible deltas, and sdd project to materialize the effective spec into .swarm/spec.md for planning.",category:"utility",toolPolicy:"agent"},"sdd status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",subcommandOf:"sdd",args:"[--json]",category:"utility",toolPolicy:"agent"},"sdd validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",subcommandOf:"sdd",args:"[--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",subcommandOf:"sdd",args:"[--dry-run] [--overwrite] [--json] [--change <id>]",category:"utility",toolPolicy:"agent"},"sdd-status":{handler:(ctx)=>handleSddStatusCommand(ctx.directory,ctx.args),description:"Show OpenSpec-compatible SDD status and effective spec source",aliasOf:"sdd status",deprecated:!0},"sdd-validate":{handler:(ctx)=>handleSddValidateCommand(ctx.directory,ctx.args),description:"Validate OpenSpec-compatible artifacts and effective spec projection",aliasOf:"sdd validate",deprecated:!0},"sdd-project":{handler:(ctx)=>handleSddProjectCommand(ctx.directory,ctx.args),description:"Materialize the OpenSpec-compatible effective spec into .swarm/spec.md",aliasOf:"sdd project",deprecated:!0},analyze:{handler:(ctx)=>handleAnalyzeCommand(ctx.directory,ctx.args),description:"Analyze spec.md vs plan.md for requirement coverage gaps",args:"",category:"agent",toolPolicy:"none"},clarify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleClarifyCommand),description:"Clarify and refine an existing feature specification",args:"[description-text]",category:"agent",toolPolicy:"none"},specify:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleSpecifyCommand),description:"Generate or import a feature specification [description]",args:"[description-text]",category:"agent",toolPolicy:"none"},brainstorm:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleBrainstormCommand),description:"Enter architect MODE: BRAINSTORM — structured seven-phase planning workflow [topic]",args:"[topic-text]",details:"Triggers the architect to run the brainstorm workflow: CONTEXT SCAN, single-question DIALOGUE, APPROACHES, DESIGN SECTIONS, SPEC WRITE + SELF-REVIEW, QA GATE SELECTION, TRANSITION. Use for new plans where requirements need to be drawn out before writing spec.md / plan.md.",category:"agent",toolPolicy:"none"},loop:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleLoopCommand),description:"Enter architect MODE: LOOP — compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [objective]",args:"<objective> [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]",details:`Triggers the architect to run the compound-engineering loop defined in ${BUNDLED_PROJECT_SKILL_ROOT}/loop/SKILL.md: BRAINSTORM (requirements) → PLAN (+ critic gate) → BUILD (execute) → REVIEW (independent reviewer + critic on the diff, report-only) → IMPROVE (phase-wrap retrospective + compounding learning capture), then evaluate stop conditions and loop for another improvement cycle if the objective is unmet and budget remains. Generator and reviewer/critic run in separate contexts; failing assertions must be fixed at the root cause, never weakened, mocked, or skipped. Defense-in-depth stop conditions: objective met, --max-cycles budget (default 3), no-progress/plateau, oscillation, unrecoverable error, or explicit user stop. --autonomy auto (default) runs unattended with hard stops still enforced; --autonomy checkpoint pauses at phase gates for user approval. --depth exhaustive widens exploration. --resume continues an existing loop run from durable .swarm/loop/ state. Distinct from full-auto (autonomous cross-phase oversight) and turbo (parallel lanes within a phase): loop is a user-initiated, gated, compounding workflow.`,category:"agent",toolPolicy:"none"},council:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCouncilCommand),description:"Enter architect MODE: COUNCIL — multi-model deliberation [question] [--spec-review]",args:"<question> [--spec-review]",details:"Triggers the architect to convene a three-agent General Council: Generalist (reviewer model), Skeptic (critic model), and Domain Expert (SME model). "+"The architect first runs 1–3 targeted web searches and passes a compiled RESEARCH CONTEXT "+"to all three agents before dispatching them in parallel. Agents deliberate using the NSED peer-review protocol (Round 1 independent analysis, Round 2 MAINTAIN/CONCEDE/NUANCE for disagreements). The architect synthesizes the final answer directly from convene_general_council output. --spec-review switches to single-pass advisory mode for spec review. Requires council.general.enabled: true and a search API key in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",category:"agent",toolPolicy:"none"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand),description:"Launch deep PR review with multi-lane analysis [url] [--council]",args:"<pr-url|owner/repo#N|N> [--council]",details:"Launches a structured PR review: reconstructs PR intent via obligation extraction cascade, launches all 6 fixed base explorer lanes through dispatch_lanes_async while the architect keeps doing non-dependent work, polls collect_lane_results incrementally, runs every triggered micro-lane, validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, then synthesizes only after coverage is closed. If lane tools cannot close coverage, Task-tool dispatch is the final verified-equivalent fallback; if equivalence cannot be proven, the review is BLOCKED rather than degraded. --council variant fires adversarial multi-model review. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"pr-feedback":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrFeedbackCommand),description:"Ingest and close known PR feedback (review comments, CI failures, conflicts) [pr] [instructions]",args:"[url|owner/repo#N|N] [instructions...]",details:"Triggers MODE: PR_FEEDBACK — ingests existing pull-request feedback (review threads, requested changes, CI/check failures, merge conflicts, stale branch state, pasted notes), verifies every claim against source, clusters related problems, fixes confirmed items, validates the branch, and reports closure status for every ledger item. Distinct from /swarm pr-review, which discovers new findings. The PR reference is optional: with none, the architect builds the ledger from the current PR/branch; text after the reference is forwarded as extra instructions. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"none"},"pr subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:'Subscribes the current session to PR state-change events for the specified PR. When pr_monitor.enabled is true, the background polling worker detects CI failures, new comments, review state changes (changes requested / approved), merge conflicts and conflict resolutions, and merge/close events — each gated by its pr_monitor notify_* config flag (notify_ci_success defaults to false). Delivery follows pr_monitor.event_delivery: "prompt" (default) wakes the subscribed session with a structured <pr-activity> message; "advisory" queues session-scoped advisories with dedup tokens for the next turn. Subscriptions are idempotent, capped by pr_monitor.max_subscriptions, and agent-callable. Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin). Requires pr_monitor.enabled: true in config.',category:"agent",toolPolicy:"agent"},"pr-subscribe":{handler:(ctx)=>handlePrSubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Subscribe the current session to PR state-change notifications",aliasOf:"pr subscribe",deprecated:!0},"pr unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",args:"<pr-url|owner/repo#N|N>",details:"Unsubscribes the current session from PR state-change events for the specified PR. Removes the active subscription record (idempotent; agent-callable). Supports full GitHub URL, owner/repo#N shorthand, or bare PR number (resolved against origin).",category:"agent",toolPolicy:"agent"},"pr-unsubscribe":{handler:(ctx)=>handlePrUnsubscribeCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Unsubscribe the current session from PR state-change notifications",aliasOf:"pr unsubscribe",deprecated:!0},"pr status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",args:"",details:"Displays all active PR subscriptions for the current session. Shows PR URL, last checked time, watching status, and error count per subscription. Also shows total active subscriptions across all sessions.",category:"agent",toolPolicy:"agent",toolNoArgs:!0},"pr-status":{handler:(ctx)=>handlePrMonitorStatusCommand(ctx.directory,ctx.args,ctx.sessionID,ctx.source),description:"Show PR monitor subscription status for the current session",aliasOf:"pr status",deprecated:!0},"ci-simulate":{handler:(ctx)=>handleCiSimulateCommand(ctx.directory,ctx.args),description:"Create a temporary merge-result worktree and run CI before merge queue entry",args:"[--base origin/main] [--head <ref>]",details:"Creates a detached temporary worktree under .swarm/ci-simulate from the base ref, merges the current worktree HEAD (or --head ref), runs fixed local CI gates (typecheck, Biome CI, build, unit/integration/security/smoke tests, drift check), then removes the worktree and prunes metadata. Intended as a pre-queue merge_group simulation helper.",category:"agent",toolPolicy:"agent"},"deep-dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Launch deep codebase audit with parallel explorer waves, dual reviewers, and critic challenge [scope]",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",details:"Runs a read-only deep audit of the specified scope using parallel explorer waves (8-file cap per mission, ~3500 line guardrail), always 2 parallel reviewers for verification, and sequential critic challenge on HIGH/CRITICAL findings. Profiles select explorer lanes: standard (5 lanes), security, ux, architecture, full (all 8 lanes). Emits a structured findings report without mutating source code.",category:"agent",toolPolicy:"none"},"deep dive":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepDiveCommand),description:"Alias for /swarm deep-dive — launch deep codebase audit",args:"<scope> [--profile standard|security|ux|architecture|full] [--max-explorers 1..8] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"deep-dive"},"deep-research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Launch a multi-source, fact-checked deep research pass and synthesize a cited report [question]",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",details:"Runs the orchestrator-worker deep-research protocol: the architect decomposes the question into subtopics, gathers evidence with web_search and web_fetch across up to N iterative rounds, dispatches parallel sme synthesis workers, verifies every claim against cited sources with dual reviewers, challenges high-stakes claims with the critic, and presents a cited report in chat. Read-only — does not mutate source code, delegate to coder, or call declare_scope. Requires council.general.enabled and a search API key.",category:"agent",toolPolicy:"none"},"deep research":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDeepResearchCommand),description:"Alias for /swarm deep-research — launch a cited deep research pass",args:"<question> [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]",category:"agent",aliasOf:"deep-research"},"codebase-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",details:"Runs the codebase-review-swarm workflow: Phase 0 inventory, selected-track depth planning, non-diluting review passes, coverage closure, reviewer validation, critic challenge, and .swarm/review-v8 artifacts. Materializes the bundled skill package if missing, then emits a MODE signal; the architect workflow must not mutate source files.",category:"agent",toolPolicy:"none"},"codebase review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCodebaseReviewCommand),description:"Alias for /swarm codebase-review - launch codebase-review-swarm",args:"[scope] [--mode phase0|complete|defect|security|correctness|testing|ui|performance|ai-slop|enhancements|custom] [--tracks <list>] [--continue <run-id>] [--json] [--skip-update] [--allow-dirty]",category:"agent",aliasOf:"codebase-review"},"design-docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Generate or sync language-agnostic design docs (domain, technical-spec, behavior-spec, reference/) for the project under build [description]",args:"<description> [--out <dir>] [--lang <name>] [--update]",details:"Triggers the architect to enter MODE: DESIGN_DOCS — delegates to the docs_design agent to author/sync docs/domain.md, docs/technical-spec.md, docs/behavior-spec.md, and docs/reference/* (plus reference/traceability.json and design-changelog.md). Normative docs are 100% language-agnostic; all framework-specific material is quarantined under reference/. --update syncs existing docs to current code/spec instead of generating fresh. Requires design_docs.enabled: true.",category:"agent",toolPolicy:"none"},"design docs":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleDesignDocsCommand),description:"Alias for /swarm design-docs — generate or sync design docs",args:"<description> [--out <dir>] [--lang <name>] [--update]",category:"agent",aliasOf:"design-docs"},issue:{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleIssueCommand),description:"Ingest a GitHub issue into the swarm workflow [url] [--plan] [--trace] [--no-repro]",args:"<issue-url|owner/repo#N|N> [--plan] [--trace] [--no-repro]",details:"Triggers the architect to enter MODE: ISSUE_INGEST — ingests a GitHub issue, restructures it into a normalized intake note, localizes root cause through hypothesis-driven tracing, and outputs a resolution spec. --plan transitions to plan creation after spec generation. --trace runs the fix workflow end-to-end (implies --plan); compose commit-pr to publish. --no-repro skips the reproduction step. Supports full GitHub URL, owner/repo#N shorthand, or bare issue number (resolves against origin remote).",category:"agent",toolPolicy:"none"},"qa-gates":{handler:(ctx)=>handleQaGatesCommand(ctx.directory,ctx.args,ctx.sessionID),description:"View or modify QA gate profile for the current plan [enable|override <gate>...]",args:"[show|enable|override] <gate>...",details:"show: display spec-level, session-override, and effective QA gates for the current plan. enable: persist gate(s) into the locked-once profile (architect; rejected after critic approval lock). override: session-only ratchet-tighter enable. Valid gates: reviewer, test_engineer, council_mode, sme_enabled, critic_pre_plan, hallucination_guard, sast_enabled, mutation_test, phase_council, drift_check, final_council.",category:"config",toolPolicy:"none"},link:{handler:(ctx)=>handleLinkCommand(ctx.directory,ctx.args),description:"Tie this worktree to a shared swarm knowledge store [name]",details:"Links the current worktree to a shared knowledge store so multiple swarms working on the same project (e.g. separate git worktrees) pool their lessons instead of each keeping an isolated .swarm/knowledge.jsonl. With no name, ties all worktrees of the same repo via the project hash; with a name, ties any worktrees/repos that use the same name. Existing local lessons are merged (deduped) into the shared store. Use `/swarm link status` to inspect.",args:"[<name> | status]",category:"utility",toolPolicy:"none"},"link status":{handler:(ctx)=>handleLinkCommand(ctx.directory,["status"]),description:"Show whether this worktree shares knowledge via a link",subcommandOf:"link",category:"utility",toolPolicy:"none"},unlink:{handler:(ctx)=>handleUnlinkCommand(ctx.directory,ctx.args),description:"Stop sharing swarm knowledge for this worktree [--no-copy]",details:"Unlinks the current worktree from its shared knowledge store and returns it to a local .swarm/knowledge.jsonl. By default the shared lessons are copied back into the local store (deduped) so nothing is lost; pass --no-copy to skip the copy-back.",args:"[--no-copy]",category:"utility",toolPolicy:"none"},promote:{handler:(ctx)=>handlePromoteCommand(ctx.directory,ctx.args),description:"Manually promote lesson to hive knowledge",details:"Promotes a lesson directly to hive knowledge (--category flag sets category) or references an existing swarm lesson by ID (--from-swarm). Validates lesson text before promotion. Either direct text or --from-swarm ID is required.",args:"--category <category>, --from-swarm <lesson-id>, <lesson-text>",category:"utility",toolPolicy:"none"},reset:{handler:(ctx)=>handleResetCommand(ctx.directory,ctx.args),description:"Clear swarm state files [--confirm]",details:"DELETES plan.md, context.md, and summaries/ directory from .swarm/. Stops background automation and clears in-memory queues. SAFETY: requires --confirm flag — without it, displays a warning and tips to export first.",args:"--confirm (required)",category:"utility",clashesWithNativeCcCommand:"/reset",toolPolicy:"restricted"},"reset-session":{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",details:"Deletes only .swarm/session/state.json and any other session files. Clears in-memory agent sessions and delegation chains. Preserves plan, evidence, and knowledge for cross-session continuity.",args:"",category:"utility",toolPolicy:"restricted"},rollback:{handler:(ctx)=>handleRollbackCommand(ctx.directory,ctx.args),description:"Restore swarm state or project files to a checkpoint",details:"Restores legacy .swarm/ phase checkpoints from checkpoints/phase-<N> when present. Otherwise restores named git checkpoints from .swarm/checkpoints.json by label or list number. Writes rollback event to events.jsonl. Without an argument, lists available checkpoints.",args:"<phase-number|label|list-number>",category:"utility",toolPolicy:"restricted"},retrieve:{handler:(ctx)=>handleRetrieveCommand(ctx.directory,ctx.args),description:"Retrieve full output from a summary <id>",args:"<summary-id>",details:"Loads the full tool output that was previously summarized (referenced by IDs like S1, S2). Use when you need the complete output instead of the truncated summary.",category:"utility",toolPolicy:"agent"},handoff:{handler:(ctx)=>handleHandoffCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Prepare state for clean model switch (new session)",args:"",details:"Generates handoff.md with full session state snapshot, including plan progress, recent decisions, and agent delegation history. Prepended to the next session prompt for seamless model switches.",category:"core",toolPolicy:"none"},turbo:{handler:(ctx)=>handleTurboCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Turbo Mode strategy for the active session [on|off|lean|standard|epic|status]",args:"on, off, lean, standard, epic, status",details:`Toggles Turbo Mode for the current session. Supports three strategies:
1936
1936
 
1937
1937
  `+`**Standard turbo** — skips non-critical QA gates for faster iteration.
1938
1938
  `+`**Lean turbo** — parallel lane execution with per-lane reviewer gates and file-lock conflict detection.
@@ -1990,7 +1990,7 @@ Present the eleven gates with their defaults (DEFAULT_QA_GATES) as a single user
1990
1990
  - drift_check (default: ON) — when enabled, mandatory per-phase drift verification via critic_drift_verifier at PHASE-WRAP; compares implemented changes against spec.md intent; hard-blocks phase_complete when spec.md exists and drift evidence is missing or REJECTED; advisory-only when no spec.md exists (recommended for all projects with a specification)
1991
1991
  - final_council (default: OFF) — when enabled, the full 5-member council (NOT the General Council) reviews the entire project after all phases complete. The architect dispatches the same five council members (\`critic\`, \`reviewer\`, \`sme\`, \`test_engineer\`, \`explorer\`) at project scope, collects \`CouncilMemberVerdict\` objects, and calls \`write_final_council_evidence\`. This is not General Council mode and does not require \`council.general.enabled\`.
1992
1992
 
1993
- Present all three items together in a single message. One message, defaults pre-stated. Wait for the user's answer to all three:
1993
+ Present all four items together in a single message. One message, defaults pre-stated. Wait for the user's answer to all four:
1994
1994
 
1995
1995
  **1. QA Gates** — accept defaults or customize (the eleven gates listed above).
1996
1996
 
@@ -1998,7 +1998,9 @@ Present all three items together in a single message. One message, defaults pre-
1998
1998
 
1999
1999
  **3. Commit Frequency** — "Commit frequency for completed tasks? (default: phase-level only; optional per-task checkpoint commit after each task completion)"
2000
2000
 
2001
- Wait for the user to answer all three in a single reply. Then apply:
2001
+ **4. Auto-proceed** "Auto-advance to the next phase without asking 'Ready for Phase N+1?'? (default: false; runtime toggle via \`/swarm auto-proceed on|off\`)"
2002
+
2003
+ Wait for the user to answer all four in a single reply. Then apply:
2002
2004
 
2003
2005
  - For gates: record the user's gate selections.
2004
2006
  - For parallel coders: if the user says a number > 1, write a \`## Pending Parallelization Config\` section to \`.swarm/context.md\` alongside the gate selection:
@@ -2018,7 +2020,9 @@ If the user accepts the default (1), skip writing this section entirely — seri
2018
2020
  - commit_after_each_completed_task: true
2019
2021
  - recorded_at: <ISO timestamp>
2020
2022
  \`\`\`
2021
- If the user keeps the default phase-level behavior, do not write this section.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2023
+ If the user keeps the default phase-level behavior, do not write this section.
2024
+
2025
+ - For auto-proceed: record the user's choice in the \`## Pending QA Gate Selection\` section of \`.swarm/context.md\` as \`- auto_proceed: <true|false>\` so it is persisted into the plan's \`execution_profile\` on save_plan.`}function buildAvailableToolsList(council,memoryEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let qaCouncilEnabled=council?.enabled===!0,generalCouncilEnabled=council?.general?.enabled===!0;return[...[...AGENT_TOOL_MAP.architect??[],...memoryEnabled?MEMORY_AGENT_TOOL_MAP.architect??[]:[],...externalSkillsEnabled?EXTERNAL_SKILL_AGENT_TOOL_MAP.architect??[]:[],...qaCouncilEnabled?COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...generalCouncilEnabled?GENERAL_COUNCIL_AGENT_TOOL_MAP.architect??[]:[],...turboEnabled?TURBO_AGENT_TOOL_MAP.architect??[]:[],...skillsEnabled?SKILL_AGENT_TOOL_MAP.architect??[]:[]]].sort().map((t)=>{let desc=TOOL_DESCRIPTIONS[t];return desc?`${t} (${desc})`:t}).join(", ")}function buildSlashCommandsList(){let SKIP_ALIASES=new Set(Object.entries(COMMAND_REGISTRY).filter(([,entry])=>entry.aliasOf).map(([name])=>name)),READ_ONLY_OBSERVATION=new Set(["status","history","agents","config","show-plan","benchmark","export","retrieve"]),CATEGORY_ORDER=["Session Lifecycle","Planning","Execution Modes","Observation","Knowledge","State Management","Diagnostics"],COMMANDS_BY_CATEGORY={"Session Lifecycle":["finalize","reset","reset-session","handoff","archive"],Planning:["specify","clarify","analyze","show-plan","sync-plan","acknowledge-spec-drift","council"],"Execution Modes":["turbo","full-auto","loop"],Observation:["status","history","agents","config","benchmark","export","evidence","evidence summary","retrieve"],Knowledge:["knowledge","knowledge migrate","knowledge quarantine","knowledge restore","promote","curate"],"State Management":["checkpoint","rollback","write-retro"],Diagnostics:["diagnose","preflight","doctor tools","config doctor","simulate","dark-matter"]},lines=[],subcommandMap={};for(let[cmdName,cmdEntry]of Object.entries(COMMAND_REGISTRY)){let entry=cmdEntry;if(entry.subcommandOf){if(!subcommandMap[entry.subcommandOf])subcommandMap[entry.subcommandOf]=[];subcommandMap[entry.subcommandOf].push(cmdName)}}let compoundsInValidCommands=new Set;for(let category of CATEGORY_ORDER){lines.push(`**${category}**`);let commandNames=COMMANDS_BY_CATEGORY[category];for(let name of commandNames){let entry=COMMAND_REGISTRY[name];if(!entry)continue;if(SKIP_ALIASES.has(name))continue;if(entry.subcommandOf&&!VALID_COMMANDS.includes(name))continue;if(lines.push(`- \`/swarm ${name}\` — ${entry.description}`),entry.subcommandOf&&VALID_COMMANDS.includes(name))compoundsInValidCommands.add(name);if(READ_ONLY_OBSERVATION.has(name))continue;if(entry.details)lines.push(` ${entry.details}`);if(entry.args)lines.push(` Args: ${entry.args}`)}for(let parent of commandNames){let subs=subcommandMap[parent];if(!subs)continue;for(let subName of subs){let subEntry=COMMAND_REGISTRY[subName];if(!subEntry)continue;if(compoundsInValidCommands.has(subName)||subEntry.subcommandOf&&VALID_COMMANDS.includes(subName)||SKIP_ALIASES.has(subName))continue;if(lines.push(` - \`/swarm ${subName}\` — ${subEntry.description}`),subEntry.details)lines.push(` ${subEntry.details}`);if(subEntry.args)lines.push(` Args: ${subEntry.args}`)}}}return lines.join(`
2022
2026
  `)}function createArchitectAgent(model,customPrompt,customAppendPrompt,adversarialTesting,council,uiReview,memoryEnabled=!1,architecturalSupervision,designDocsEnabled=!1,externalSkillsEnabled=!1,turboEnabled=!1,skillsEnabled=!1){let prompt=ARCHITECT_PROMPT;prompt=resolvePrompt(prompt,customPrompt,customAppendPrompt),prompt=prompt?.replace("{{YOUR_TOOLS}}",buildYourToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{AVAILABLE_TOOLS}}",buildAvailableToolsList(council,memoryEnabled,externalSkillsEnabled,turboEnabled,skillsEnabled))?.replace("{{SLASH_COMMANDS}}",buildSlashCommandsList()),prompt=prompt?.replace(/\{\{QA_GATE_DIALOGUE_SPECIFY\}\}/g,buildQaGateSelectionDialogue("SPECIFY"))?.replace(/\{\{QA_GATE_DIALOGUE_BRAINSTORM\}\}/g,buildQaGateSelectionDialogue("BRAINSTORM"))?.replace(/\{\{QA_GATE_DIALOGUE_PLAN\}\}/g,buildQaGateSelectionDialogue("PLAN"));let councilBlock=buildCouncilWorkflow(council),hasPlaceholder=prompt?.includes("{{COUNCIL_WORKFLOW}}")===!0;if(councilBlock==="")prompt=prompt?.replace(/\n\n\{\{COUNCIL_WORKFLOW\}\}\n\n/g,`
2023
2027
 
2024
2028
  `);else if(hasPlaceholder)prompt=prompt?.replace(/\{\{COUNCIL_WORKFLOW\}\}/g,councilBlock);else prompt=`${prompt??""}
@@ -2893,7 +2897,7 @@ HARD CONSTRAINTS (apply regardless of skill load success):
2893
2897
  ### MODE: ISSUE_INGEST
2894
2898
  Activates when the user invokes /swarm issue <url> or the architect receives an ISSUE_INGEST signal.
2895
2899
 
2896
- Purpose: Ingest issue evidence, trace impact, and transition to planning or tracing.
2900
+ Purpose: Ingest issue evidence, trace impact, and transition to the full fix workflow.
2897
2901
 
2898
2902
  ACTION: Load skill ${bundledProjectSkillFileReference("issue-ingest")} immediately. Follow the protocol defined there.
2899
2903
 
@@ -4310,7 +4314,7 @@ CHANGELOG (design-changelog.md):
4310
4314
  - This is SEPARATE from CHANGELOG.md and docs/releases/pending/* (release-please owns those). NEVER touch release files here.
4311
4315
  - Append an entry per generate/sync: \`- <ISO date> phase <N>: <sections touched> (<FR refs>)\` under \`## [Unreleased]\` using Keep a Changelog headings (Added/Changed/Removed).
4312
4316
 
4313
- GUARDRAIL NOTE: if a spec-staleness block is reported when you try to write, surface it (SPEC_STALENESS_BLOCK) rather than retrying blindly — the architect resolves spec staleness first.
4317
+ GUARDRAIL NOTE: if a spec-staleness block is reported when you try to write, surface it (SPEC_DRIFT_BLOCK) rather than retrying blindly — the architect resolves spec staleness first.
4314
4318
 
4315
4319
  ## QUALITY RULES
4316
4320
  - Normative docs (domain/technical-spec/behavior-spec) describe WHAT each boundary guarantees, not which library provides it.
@@ -5311,7 +5315,7 @@ ${currentPhase!==void 0?"- **Phase Status**: Pending completion":""}
5311
5315
  ## Resolution
5312
5316
  This escalation requires human intervention. The swarm has been paused.
5313
5317
  Please review the architect's output above and provide guidance.
5314
- `;fs81.writeFileSync(reportPath,reportContent,"utf-8"),log(`[full-auto-intercept] Escalation report written to: ${reportPath}`)}catch(error93){error48("[full-auto-intercept] Failed to write escalation report:",error93 instanceof Error?error93.message:String(error93))}}async function handleEscalation(directory,reason,sessionID,architectOutput,interactionCount,deadlockCount,escalationMode,phase){if(telemetry.autoOversightEscalation(sessionID??"unknown",reason,interactionCount,deadlockCount,phase),await writeEscalationReport(directory,reason,architectOutput,interactionCount,deadlockCount,phase),escalationMode==="terminate"){if(error48(`[full-auto-intercept] ESCALATION (terminate mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});terminateFullAutoRun(directory,sessionID,reason)}return!0}if(warn(`[full-auto-intercept] ESCALATION (pause mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});pauseFullAutoRun(directory,sessionID,reason)}return!0}var reactiveOversightSequence=0;async function mirrorReactiveVerdictToV2(params){reactiveOversightSequence+=1;let triggerSource=params.escalationType==="phase_completion"?"phase_boundary":"text_pattern",sessionID="",phase,planID;try{let filePath=validateSwarmPath(params.directory,"full-auto-state.json");if(fs81.existsSync(filePath)){let raw=fs81.readFileSync(filePath,"utf-8"),persisted=JSON.parse(raw);if(persisted.sessions){let callerSid=params.sessionID;if(callerSid&&persisted.sessions[callerSid]){let rec=persisted.sessions[callerSid];if(rec.status==="running")sessionID=callerSid,phase=rec.currentPhase,planID=rec.planID}else if(!callerSid)for(let sid of Object.keys(persisted.sessions)){let rec=persisted.sessions[sid];if(rec?.status==="running"){sessionID=sid,phase=rec.currentPhase,planID=rec.planID;break}}}}}catch{}if(!sessionID)return;let decision=(()=>{if(params.parsed.escalationNeeded||params.parsed.verdict==="ESCALATE_TO_HUMAN")return"escalate_human";if(params.parsed.verdict==="APPROVED"||params.parsed.verdict==="ANSWER")return"allow";if(params.parsed.verdict==="BLOCKED")return"pause";if(params.parsed.verdict==="PENDING")return"pending";return"deny"})(),beforeStatus=sessionID?loadFullAutoRunState(params.directory,sessionID)?.status:void 0,event={type:"full_auto_oversight",timestamp:new Date().toISOString(),session_id:sessionID,plan_id:planID,phase,trigger_source:triggerSource,trigger_reason:`reactive intercept (${params.escalationType})`,critic_agent:params.oversightAgentName,critic_model:params.criticModel,verdict:params.parsed.verdict,reasoning:params.parsed.reasoning,evidence_checked:params.parsed.evidenceChecked,anti_patterns_detected:params.parsed.antiPatternsDetected,escalation_needed:params.parsed.escalationNeeded,decision,full_auto_status_before:beforeStatus,full_auto_status_after:beforeStatus,oversight_sequence:reactiveOversightSequence};if(sessionID){if(decision==="pause")pauseFullAutoRun(params.directory,sessionID,`reactive verdict ${params.parsed.verdict}`),event.full_auto_status_after="paused";else if(decision==="escalate_human")terminateFullAutoRun(params.directory,sessionID,"reactive ESCALATE_TO_HUMAN"),event.full_auto_status_after="terminated";recordFullAutoOversight(params.directory,sessionID,params.parsed.verdict,`reactive ${params.escalationType}`)}if(await writeFullAutoOversightEvent(params.directory,event),params.escalationType==="phase_completion"&&params.parsed.verdict==="APPROVED"&&typeof phase==="number")await writeFullAutoOversightEvidence(params.directory,phase,event)}init_guardrails2();function isPartsShape(message){let info=message.info;return typeof info==="object"&&info!==null&&typeof info.role==="string"&&Array.isArray(message.parts)}function getRole(message){if(isPartsShape(message))return message.info.role;return message.role}function isToolResultSystemMessage(message){if(isPartsShape(message))return!1;let flat=message;return flat.tool_call_id!==void 0||flat.name!==void 0}function getSystemText(message){if(isPartsShape(message)){let texts=message.parts.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5318
+ `;fs81.writeFileSync(reportPath,reportContent,"utf-8"),log(`[full-auto-intercept] Escalation report written to: ${reportPath}`)}catch(error93){error48("[full-auto-intercept] Failed to write escalation report:",error93 instanceof Error?error93.message:String(error93))}}async function handleEscalation(directory,reason,sessionID,architectOutput,interactionCount,deadlockCount,escalationMode,phase){if(telemetry.autoOversightEscalation(sessionID??"unknown",reason,interactionCount,deadlockCount,phase),await writeEscalationReport(directory,reason,architectOutput,interactionCount,deadlockCount,phase),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});recordFullAutoEscalation(directory,sessionID,{reason,interactionCount,deadlockCount,phase})}if(escalationMode==="terminate"){if(error48(`[full-auto-intercept] ESCALATION (terminate mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});terminateFullAutoRun(directory,sessionID,reason)}return!0}if(warn(`[full-auto-intercept] ESCALATION (pause mode) — reason: ${reason}, session: ${sessionID}`),sessionID){if(!loadFullAutoRunState(directory,sessionID))startFullAutoRun(directory,sessionID,{enabled:!0});pauseFullAutoRun(directory,sessionID,reason)}return!0}var reactiveOversightSequence=0;async function mirrorReactiveVerdictToV2(params){reactiveOversightSequence+=1;let triggerSource=params.escalationType==="phase_completion"?"phase_boundary":"text_pattern",sessionID="",phase,planID;try{let filePath=validateSwarmPath(params.directory,"full-auto-state.json");if(fs81.existsSync(filePath)){let raw=fs81.readFileSync(filePath,"utf-8"),persisted=JSON.parse(raw);if(persisted.sessions){let callerSid=params.sessionID;if(callerSid&&persisted.sessions[callerSid]){let rec=persisted.sessions[callerSid];if(rec.status==="running")sessionID=callerSid,phase=rec.currentPhase,planID=rec.planID}else if(!callerSid)for(let sid of Object.keys(persisted.sessions)){let rec=persisted.sessions[sid];if(rec?.status==="running"){sessionID=sid,phase=rec.currentPhase,planID=rec.planID;break}}}}}catch{}if(!sessionID)return;let decision=(()=>{if(params.parsed.escalationNeeded||params.parsed.verdict==="ESCALATE_TO_HUMAN")return"escalate_human";if(params.parsed.verdict==="APPROVED"||params.parsed.verdict==="ANSWER")return"allow";if(params.parsed.verdict==="BLOCKED")return"pause";if(params.parsed.verdict==="PENDING")return"pending";return"deny"})(),beforeStatus=sessionID?loadFullAutoRunState(params.directory,sessionID)?.status:void 0,event={type:"full_auto_oversight",timestamp:new Date().toISOString(),session_id:sessionID,plan_id:planID,phase,trigger_source:triggerSource,trigger_reason:`reactive intercept (${params.escalationType})`,critic_agent:params.oversightAgentName,critic_model:params.criticModel,verdict:params.parsed.verdict,reasoning:params.parsed.reasoning,evidence_checked:params.parsed.evidenceChecked,anti_patterns_detected:params.parsed.antiPatternsDetected,escalation_needed:params.parsed.escalationNeeded,decision,full_auto_status_before:beforeStatus,full_auto_status_after:beforeStatus,oversight_sequence:reactiveOversightSequence};if(sessionID){if(decision==="pause")pauseFullAutoRun(params.directory,sessionID,`reactive verdict ${params.parsed.verdict}`),event.full_auto_status_after="paused";else if(decision==="escalate_human")terminateFullAutoRun(params.directory,sessionID,"reactive ESCALATE_TO_HUMAN"),event.full_auto_status_after="terminated";recordFullAutoOversight(params.directory,sessionID,params.parsed.verdict,`reactive ${params.escalationType}`)}if(await writeFullAutoOversightEvent(params.directory,event),params.escalationType==="phase_completion"&&params.parsed.verdict==="APPROVED"&&typeof phase==="number")await writeFullAutoOversightEvidence(params.directory,phase,event)}init_guardrails2();function isPartsShape(message){let info=message.info;return typeof info==="object"&&info!==null&&typeof info.role==="string"&&Array.isArray(message.parts)}function getRole(message){if(isPartsShape(message))return message.info.role;return message.role}function isToolResultSystemMessage(message){if(isPartsShape(message))return!1;let flat=message;return flat.tool_call_id!==void 0||flat.name!==void 0}function getSystemText(message){if(isPartsShape(message)){let texts=message.parts.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5315
5319
  `):null}let content=message.content;if(typeof content==="string"){let trimmed=content.trim();return trimmed.length>0?trimmed:null}if(Array.isArray(content)){let texts=content.filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text.trim()).filter((t)=>t.length>0);return texts.length>0?texts.join(`
5316
5320
  `):null}return null}function isWhitespaceOnlySystem(message){if(getRole(message)!=="system")return!1;if(isPartsShape(message))return message.parts.length>0&&message.parts.every((part)=>part.type!=="text"||typeof part.text!=="string"||part.text.trim().length===0);let content=message.content;return typeof content==="string"&&content.trim().length===0}function buildConsolidatedSystem(firstSystem,mergedText){if(isPartsShape(firstSystem))return{...firstSystem,info:{...firstSystem.info,role:"system"},parts:[{type:"text",text:mergedText}]};return{role:"system",content:mergedText,...Object.fromEntries(Object.entries(firstSystem).filter(([key])=>key!=="role"&&key!=="content"&&key!=="name"&&key!=="tool_call_id"))}}function consolidateSystemMessages(messages){if(messages.length>0&&getRole(messages[0])==="system"&&getSystemText(messages[0])!==null&&(isPartsShape(messages[0])||typeof messages[0].content==="string")){if(messages.filter((m)=>getRole(m)==="system").length===1)return[...messages]}let systemMessageIndices=[],systemContents=[];for(let i=0;i<messages.length;i++){let message=messages[i];if(getRole(message)!=="system")continue;if(isToolResultSystemMessage(message))continue;let textContent=getSystemText(message);if(systemMessageIndices.push(i),textContent)systemContents.push(textContent)}if(systemContents.length===0)return messages.filter((m,idx)=>{if(getRole(m)!=="system")return!0;return idx===0});let mergedSystemContent=systemContents.join(`
5317
5321
 
@@ -6070,7 +6074,7 @@ ${tailContent.join(`
6070
6074
  `)}
6071
6075
  ${footerLines.join(`
6072
6076
  `)}`}init_warning_buffer();var _heartbeatTimers=new Map,SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path237.resolve(path237.dirname(fileURLToPath5(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000;function createSwarmCommandSystemRuleHook(agentDefinitions,registeredAgents){return async(input,output)=>{let{sessionID}=input,activeAgentName=sessionID?swarmState.activeAgent.get(sessionID):void 0;if(!agentHasSwarmCommandTool(activeAgentName,agentDefinitions,registeredAgents))return;let system=Array.isArray(output.system)?output.system:[];if(system.some((entry)=>entry.includes(SWARM_COMMAND_SYSTEM_RULE_TAG))){output.system=system;return}system.push([SWARM_COMMAND_SYSTEM_RULE_TAG,"When a user asks for a supported /swarm command and the message instructs you to call the `swarm_command` tool, call that tool exactly once with the provided JSON arguments. After the tool returns, show the tool output verbatim and do not add extra swarm state, summaries, or invented command output."].join(`
6073
- `)),output.system=system}}var OpenCodeSwarm=async(ctx)=>{try{return await initializeOpenCodeSwarm(ctx)}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=isPlainRecord(input)?input.event:void 0;if(!isPlainRecord(event))return;if(event.type==="message.updated"){let properties=isPlainRecord(event.properties)?event.properties:void 0,info=isPlainRecord(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord(event.properties)?event.properties:void 0,part=isPlainRecord(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||!isPlainRecord(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate=value[key];if(typeof candidate==="string"&&candidate.trim()!=="")found.push(candidate)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function resolveDelegationModel(config3,agentName,baseAgentName){let topLevelModel=config3.agents?.[agentName]?.model??config3.agents?.[baseAgentName]?.model;if(topLevelModel)return topLevelModel;let swarmID=inferSwarmID(agentName,baseAgentName),swarmAgents=swarmID?config3.swarms?.[swarmID]?.agents:void 0;return swarmAgents?.[agentName]?.model??swarmAgents?.[baseAgentName]?.model??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default}function inferSwarmID(agentName,baseAgentName){if(!agentName||agentName===baseAgentName)return;for(let separator of["_","-"," "]){let suffix=`${separator}${baseAgentName}`;if(agentName.endsWith(suffix)&&agentName.length>suffix.length)return agentName.slice(0,-suffix.length)}return}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx){clearDeferredWarnings();let{config:config3,loadedFromFile}=await loadPluginConfigWithMetaAsync(ctx.directory);if(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,await withTimeout(loadSnapshot(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})}),initTelemetry(ctx.directory);let repoGraphHook=createRepoGraphBuilderHook(ctx.directory,void 0,{excludeDirs:config3.repo_graph?.exclude_dirs});if(queueMicrotask(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))}),await withTimeout(ensureSwarmGitExcluded(ctx.directory,{quiet:config3.quiet}),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})}),queueMicrotask(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),queueMicrotask(()=>{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)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}),agents=getAgentConfigs(config3,ctx.directory,void 0,projectContext??void 0),agentDefinitions=createAgents(config3,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent]));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=Object.keys(agents);let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),contextBudgetHandler=createContextBudgetHandler(config3),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:(sessionID)=>swarmState.activeAgent.get(sessionID),packageRoot:PACKAGE_ROOT2,registeredAgents:agents}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(config3,ctx.directory),backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory}),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}),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),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({}),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),advisoryInjector=(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(message)},scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),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:AutoReviewConfigSchema.parse(config3.auto_review??{}),directory:ctx.directory,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")queueMicrotask(()=>{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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=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=path237.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{new PlanSyncWorker({directory:ctx.directory}).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)queueMicrotask(()=>{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(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{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;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&&doctorResult.appliedFixes.length>0){let msg=`[opencode-swarm] Config Doctor applied ${doctorResult.appliedFixes.length} fix(es) automatically.`;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),event:async(input)=>{try{if(rememberAssistantUsageEvent(input),prEventDelivery){let evt=input.event;if(evt?.type==="session.idle"&&typeof evt.properties?.sessionID==="string")prEventDelivery.noteSessionIdle(evt.properties.sessionID)}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);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-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) [--preset <name>] [--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-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-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-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-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-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 p=input;if(p.sessionID){let archAgent=swarmState.activeAgent.get(p.sessionID),archSession=swarmState.agentSessions.get(p.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(p.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,guardrailsHooks.messagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(input,output)=>{try{let p=input;return knowledgeApplicationTransformScan(ctx.directory,output,p.sessionID)}catch{return Promise.resolve()}},(input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let p=input;return skillPropagationTransformScan(ctx.directory,output,p.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(output.messages)output.messages=consolidateSystemMessages(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"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()),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,(_input,output)=>{if(Array.isArray(output.system)&&output.system.length>1)output.system=[output.system.join(`
6077
+ `)),output.system=system}}var OpenCodeSwarm=async(ctx)=>{try{return await initializeOpenCodeSwarm(ctx)}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=isPlainRecord(input)?input.event:void 0;if(!isPlainRecord(event))return;if(event.type==="message.updated"){let properties=isPlainRecord(event.properties)?event.properties:void 0,info=isPlainRecord(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord(event.properties)?event.properties:void 0,part=isPlainRecord(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||!isPlainRecord(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate=value[key];if(typeof candidate==="string"&&candidate.trim()!=="")found.push(candidate)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function resolveDelegationModel(config3,agentName,baseAgentName){let topLevelModel=config3.agents?.[agentName]?.model??config3.agents?.[baseAgentName]?.model;if(topLevelModel)return topLevelModel;let swarmID=inferSwarmID(agentName,baseAgentName),swarmAgents=swarmID?config3.swarms?.[swarmID]?.agents:void 0;return swarmAgents?.[agentName]?.model??swarmAgents?.[baseAgentName]?.model??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default}function inferSwarmID(agentName,baseAgentName){if(!agentName||agentName===baseAgentName)return;for(let separator of["_","-"," "]){let suffix=`${separator}${baseAgentName}`;if(agentName.endsWith(suffix)&&agentName.length>suffix.length)return agentName.slice(0,-suffix.length)}return}function isPlainRecord(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx){clearDeferredWarnings();let{config:config3,loadedFromFile}=await loadPluginConfigWithMetaAsync(ctx.directory);if(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,await withTimeout(loadSnapshot(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})}),initTelemetry(ctx.directory);let repoGraphHook=createRepoGraphBuilderHook(ctx.directory,void 0,{excludeDirs:config3.repo_graph?.exclude_dirs});if(queueMicrotask(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))}),await withTimeout(ensureSwarmGitExcluded(ctx.directory,{quiet:config3.quiet}),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})}),queueMicrotask(()=>{runInitOrphanRecovery(ctx.directory).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("initOrphanRecovery failed (non-fatal)",{error:msg})})}),writeSwarmConfigExampleIfNew(ctx.directory),writeProjectConfigIfNew(ctx.directory,config3.quiet),queueMicrotask(()=>{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)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}),agents=getAgentConfigs(config3,ctx.directory,void 0,projectContext??void 0),agentDefinitions=createAgents(config3,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent]));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=Object.keys(agents);let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),contextBudgetHandler=createContextBudgetHandler(config3),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:(sessionID)=>swarmState.activeAgent.get(sessionID),packageRoot:PACKAGE_ROOT2,registeredAgents:agents}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(config3,ctx.directory),backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory}),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}),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),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({}),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),advisoryInjector=(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(message)},scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),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:AutoReviewConfigSchema.parse(config3.auto_review??{}),directory:ctx.directory,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")queueMicrotask(()=>{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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(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)s.pendingAdvisoryMessages??=[],s.pendingAdvisoryMessages.push(message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=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=path237.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{new PlanSyncWorker({directory:ctx.directory}).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)queueMicrotask(()=>{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(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{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;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&&doctorResult.appliedFixes.length>0){let msg=`[opencode-swarm] Config Doctor applied ${doctorResult.appliedFixes.length} fix(es) automatically.`;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),event:async(input)=>{try{if(rememberAssistantUsageEvent(input),prEventDelivery){let evt=input.event;if(evt?.type==="session.idle"&&typeof evt.properties?.sessionID==="string")prEventDelivery.noteSessionIdle(evt.properties.sessionID)}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);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-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-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-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-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-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-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 p=input;if(p.sessionID){let archAgent=swarmState.activeAgent.get(p.sessionID),archSession=swarmState.agentSessions.get(p.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(p.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,guardrailsHooks.messagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(input,output)=>{try{let p=input;return knowledgeApplicationTransformScan(ctx.directory,output,p.sessionID)}catch{return Promise.resolve()}},(input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let p=input;return skillPropagationTransformScan(ctx.directory,output,p.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(output.messages)output.messages=consolidateSystemMessages(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"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()),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,(_input,output)=>{if(Array.isArray(output.system)&&output.system.length>1)output.system=[output.system.join(`
6074
6078
 
6075
6079
  `)];return Promise.resolve()}].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)}}await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:input.agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:input.agent,sessionID:input.sessionID,args:input.args},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);skillSession.pendingAdvisoryMessages??=[],skillSession.pendingAdvisoryMessages.push(skillResult.reason)}if(skillResult.recommendedSkills&&skillResult.recommendedSkills.length>0){let argsRecord=input.args,promptRaw=argsRecord.prompt;if(typeof promptRaw==="string"){let parsedDelegation=parseDelegationArgs(input.args);if(parsedDelegation){if(!parsedDelegation.skillsField.trim()){let qualified=skillResult.recommendedSkills.filter((s)=>s.score>=0.5);if(qualified.length===0){if(argsRecord.prompt=`SKILLS: none
6076
6080