opencode-swarm 7.143.3 → 7.143.4

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 (48) hide show
  1. package/dist/cli/{config-doctor-ddbwxt14.js → config-doctor-az6nqawx.js} +2 -2
  2. package/dist/cli/{core-gfk2tsre.js → core-a6rzajem.js} +1 -1
  3. package/dist/cli/{curator-llm-factory-z23scnwb.js → curator-llm-factory-j42j5rcr.js} +17 -17
  4. package/dist/cli/{curator-hkcd03bx.js → curator-tbw9przg.js} +17 -17
  5. package/dist/cli/{evidence-summary-service-cbhsye6e.js → evidence-summary-service-3f319cst.js} +6 -6
  6. package/dist/cli/{gate-evidence-5xd9j34y.js → gate-evidence-k2yycngf.js} +2 -2
  7. package/dist/cli/{guardrail-explain-49vn7rv6.js → guardrail-explain-tsgsw91f.js} +18 -18
  8. package/dist/cli/{guardrail-log-ghymef5s.js → guardrail-log-70cxb3va.js} +3 -3
  9. package/dist/cli/{hive-promoter-akf3x240.js → hive-promoter-nksqxfs4.js} +17 -17
  10. package/dist/cli/{index-9py8e0dk.js → index-19wyta2k.js} +3 -3
  11. package/dist/cli/{index-etxy4vz9.js → index-5qqyvwqw.js} +4 -4
  12. package/dist/cli/{index-vdkywste.js → index-6htwcbxh.js} +1 -1
  13. package/dist/cli/{index-ds7j4hth.js → index-8fq18k02.js} +3 -3
  14. package/dist/cli/{index-e1feasna.js → index-8qmnqd6g.js} +1 -1
  15. package/dist/cli/{index-6cgp4ska.js → index-9m5gz9ea.js} +2 -2
  16. package/dist/cli/{index-xq2effek.js → index-bt47jrhx.js} +2 -2
  17. package/dist/cli/{index-30yyh3m0.js → index-c9d5y70c.js} +3 -3
  18. package/dist/cli/{index-64pk7525.js → index-dmtq7tvd.js} +1 -1
  19. package/dist/cli/{index-1y0rggw0.js → index-f39n8pbr.js} +1 -1
  20. package/dist/cli/{index-vatqcjnd.js → index-f3xf9dv5.js} +5 -5
  21. package/dist/cli/{index-3qw0bsgr.js → index-gbr0jbxy.js} +1 -1
  22. package/dist/cli/{index-m7gss7zy.js → index-gz3z9d64.js} +57 -49
  23. package/dist/cli/{index-e3g0t29w.js → index-ja15rdzd.js} +1 -1
  24. package/dist/cli/{index-x90gktjx.js → index-jmgm1npc.js} +1 -1
  25. package/dist/cli/{index-tj18fe58.js → index-mewk624g.js} +19 -19
  26. package/dist/cli/{index-qykq6vge.js → index-seedt8m3.js} +3 -3
  27. package/dist/cli/{index-86tn52b3.js → index-td2ga37v.js} +1 -1
  28. package/dist/cli/{index-a6rnw33a.js → index-v9qmhrj9.js} +2 -2
  29. package/dist/cli/{index-4mr3ga48.js → index-z0j133c4.js} +1 -1
  30. package/dist/cli/{index-1et48zgf.js → index-z4g05zbr.js} +1 -1
  31. package/dist/cli/index.js +17 -17
  32. package/dist/cli/{knowledge-escalator-mgg6kvva.js → knowledge-escalator-8akk4n18.js} +6 -6
  33. package/dist/cli/{knowledge-events-yjmkrrv2.js → knowledge-events-51qk8fq2.js} +4 -4
  34. package/dist/cli/{knowledge-store-647twyjp.js → knowledge-store-7rsezhav.js} +1 -1
  35. package/dist/cli/{knowledge-validator-0nsax3n6.js → knowledge-validator-nq75s9et.js} +2 -2
  36. package/dist/cli/{scan-cursor-vgmzg5ys.js → scan-cursor-em4vrcw6.js} +2 -2
  37. package/dist/cli/{schema-mzh2tam4.js → schema-1wmfgtm9.js} +1 -1
  38. package/dist/cli/{scope-persistence-m4ah4fay.js → scope-persistence-8ehnjgsg.js} +4 -4
  39. package/dist/cli/{skill-generator-eyf32w7h.js → skill-generator-3jstr1sx.js} +7 -7
  40. package/dist/cli/{worktree-isolation-grxn94v9.js → worktree-isolation-cc3x13ng.js} +17 -17
  41. package/dist/commands/registry.d.ts +2 -2
  42. package/dist/hooks/review-receipt-collector.d.ts +1 -0
  43. package/dist/index.d.ts +6 -1
  44. package/dist/index.js +12 -12
  45. package/dist/session/snapshot-reader.d.ts +11 -0
  46. package/dist/state.d.ts +4 -3
  47. package/dist/tools/dispatch-lanes.d.ts +1 -0
  48. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.143.3",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.143.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","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -664,7 +664,7 @@ ${result.stdout}`;if(/CONFLICT/i.test(combinedOutput)||/conflict/i.test(combined
664
664
  `),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{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((resolve28)=>{try{let child=execFile2("git",["-C",directory,"worktree","list","--porcelain"],{timeout:GIT_TIMEOUT_MS3,windowsHide:!0,encoding:"utf-8"},(err,stdout)=>{if(err||typeof stdout!=="string"){resolve28(0);return}let count=0;for(let line of stdout.split(`
665
665
  `))if(line.startsWith("worktree "))count++;resolve28(count)});try{child.stdin?.end()}catch{}child.on("error",()=>resolve28(0))}catch{resolve28(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)advisoryWarn(`[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_MS3=1500,MAX_SUGGESTED_SESSIONS=500,_suggestedSessions;var init_worktree_link_suggestion=__esm(()=>{init_knowledge_link();init_warning_buffer();_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 fs34 from"node:fs";import*as path58 from"node:path";function setOnSubscriptionCreated(callback){onSubscriptionCreated=callback}function storePath2(directory){return validateSwarmPath(directory,PR_SUBSCRIPTIONS_FILE)}function ensureSwarmDir3(directory){fs34.mkdirSync(path58.resolve(directory,".swarm","pr-monitor"),{recursive:!0})}function buildCorrelationId(sessionID,repoFullName,prNumber){return`${sessionID}::${repoFullName}::${prNumber}`}function readAllRecords(directory){let raw;try{raw=fs34.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(`
666
666
  `)){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 appendRecord3(directory,record2){let result=RecordSchema2.safeParse(record2);if(!result.success)throw Error(`Invalid subscription record: ${result.error.message}`);ensureSwarmDir3(directory),fs34.appendFileSync(storePath2(directory),`${JSON.stringify(record2)}
667
- `,"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),now2=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:now2,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now2,updatedAt:now2,errorCount:0};return appendRecord3(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 now2=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now2};return appendRecord3(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 appendRecord3(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now2=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=now2-record2.updatedAt>ttlMs;if(isMerged){appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now2}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now2}),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,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearGateDenialCount:()=>clearGateDenialCount,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals49,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID12}from"node:crypto";import*as fs35 from"node:fs/promises";import*as path59 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint)=>({...fingerprint}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}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.lastBudgetBySession.clear(),swarmState.liveContextWindows.clear(),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.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});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 isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID12(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now2){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key,entry]of generations){if(entry.status==="claimed")continue;if(!Number.isFinite(entry.createdAt)||now2<entry.createdAt||now2-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return null;let now2=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now2);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key2);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],status:"collecting",createdAt:now2};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now2=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now2);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="ready")return!0;return matches[0].status="ready",matches[0].readyAt=now2,!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint)=>({...fingerprint})),createdAt:generation.createdAt,readyAt:generation.readyAt,consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file2)=>declared.has(file2)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now2=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now2-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,now2=Date.now()){if(now2-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now2,sweepStaleSessions(staleDurationMs,now2)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now2=Date.now();sweepStaleSessions(staleDurationMs,now2);let sessionState={agentName,lastToolCallTime:now2,lastAgentEventTime:now2,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask: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,taskWorkflowCache:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID12(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,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,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now2)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals49.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals49.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){let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now2=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=now2,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;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.completionGateWarnedForTask)session.completionGateWarnedForTask=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.taskWorkflowCache)session.taskWorkflowCache=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.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID12();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;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.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now2,maybeSweepStaleSessions(),session}if(_internals49.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}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),newId=(session.lastInvocationIdByAgent[stripped]||0)+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now2=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now2,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now2,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 now2=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now2-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 ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.filter((file2)=>typeof file2==="string"&&file2.length>0))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file2){if(typeof file2!=="string"||file2.length===0)return!1;let existing=getModifiedFilesForTask(session,taskId);if(existing.includes(file2))return!0;return recordModifiedFilesForTask(session,taskId,[...existing,file2])}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides){let cache=ensureTaskWorkflowCache(session),existing=cache.get(taskId);cache.set(taskId,{generation:overrides.generation??existing?.generation??0,retryCount:overrides.retryCount??existing?.retryCount??0,lastOutcome:overrides.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides.updatedAt??existing?.updatedAt??""})}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=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState);if(currentIndex===-1||newIndex===-1||newIndex<=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>=LINEAR_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),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState==="complete")session.stageBCompletion?.delete(taskId),completeModifiedFilesForTask(session,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=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState);if(currentIndex===-1||newIndex===-1||newIndex<=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>=LINEAR_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"||newState==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState,options,councilConfig)}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),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}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.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,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"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence2){let snapshot=getTaskWorkflowSnapshot(evidence2);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path59.join(directory,".swarm","plan.json"),content=await fs35.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=path59.join(directory,".swarm","evidence"),entries=await fs35.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=path59.join(evidenceDir,entry.name),content=await fs35.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);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.taskWorkflowCache)session.taskWorkflowCache=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),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence2=evidenceMap.get(taskId);if(evidence2){let derivedWorkflow=evidenceToWorkflowState(evidence2);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence2]of evidenceMap){let council=evidence2.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence2);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);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 _internals49.buildRehydrationCache(directory),_internals49.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 setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map2=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map2.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;if(identity&&!liveContextIdentityMatches(cached2,identity))return;return cached2.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;return{modelID:cached2.modelID,providerID:cached2.providerID}}function evictOldestLiveContextWindow(map2,sessionID){if(map2.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map2=swarmState.lastBudgetBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{pct,tokens}),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}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 buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map2=swarmState.gateDenialCounts,existing=map2.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{count,directiveKey}),map2.size>MAX_TRACKED_GATE_DENIALS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.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,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals49;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,LINEAR_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,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals49={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});function normalizeMessage(message){return message.replace(/\s+/g," ").trim().toLowerCase()}function pushAdvisory(session,message,opts){if(!message?.trim())return!1;if(session.pendingAdvisoryMessages??=[],opts?.dedupeKey){let key=opts.dedupeKey;if(session.pendingAdvisoryMessages.some((m)=>m.includes(key)))return!1}else if(session.pendingAdvisoryMessages.some((m)=>normalizeMessage(m)===normalizeMessage(message)))return!1;let cap=Math.max(1,opts?.maxPending??25);while(session.pendingAdvisoryMessages.length>=cap)session.pendingAdvisoryMessages.shift();return session.pendingAdvisoryMessages.push(message),!0}import{promises as fs36}from"node:fs";import path60 from"node:path";function isPathSafe2(targetPath,basePath){let resolvedTarget=path60.resolve(targetPath),resolvedBase=path60.resolve(basePath),rel=path60.relative(resolvedBase,resolvedTarget);return!rel.startsWith("..")&&!path60.isAbsolute(rel)}function isWithinReplaysDir(targetPath){let parts=path60.resolve(targetPath).split(path60.sep);for(let i=0;i<parts.length-1;i++)if(parts[i]===".swarm"&&parts[i+1]==="replays")return!0;return!1}function sanitizeFilename(input){return input.replace(/[^a-zA-Z0-9_-]/g,"_")}async function startReplayRecording(sessionID,directory){try{let replayDir=path60.join(directory,".swarm","replays"),filename=`${sanitizeFilename(sessionID)}-${Date.now()}.jsonl`,filepath=path60.join(replayDir,filename);if(!isPathSafe2(filepath,replayDir))return advisoryWarn(`[replay] Invalid path detected - path traversal attempt blocked for session ${sessionID}`),null;return await fs36.mkdir(replayDir,{recursive:!0}),filepath}catch(err){return log(`[replay] Failed to start recording for session ${sessionID}: ${err}`),null}}async function recordReplayEntry(artifactPath,sessionID,entry){try{if(!isWithinReplaysDir(artifactPath)){log(`[replay] Invalid artifact path - not within .swarm/replays/: ${artifactPath}`);return}let fullEntry={timestamp:new Date().toISOString(),sessionID,...entry},line=`${JSON.stringify(fullEntry)}
667
+ `,"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),now2=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:now2,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now2,updatedAt:now2,errorCount:0};return appendRecord3(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 now2=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now2};return appendRecord3(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 appendRecord3(directory,updated),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now2=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=now2-record2.updatedAt>ttlMs;if(isMerged){appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now2}),swept+=1,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)appendRecord3(directory,{...record2,status:"expired",isWatching:!1,updatedAt:now2}),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,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearGateDenialCount:()=>clearGateDenialCount,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals49,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID12}from"node:crypto";import*as fs35 from"node:fs/promises";import*as path59 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint)=>({...fingerprint}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}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.lastBudgetBySession.clear(),swarmState.liveContextWindows.clear(),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.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],_rehydrationCache=null,swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});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 isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID12(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now2){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key,entry]of generations){if(entry.status==="claimed")continue;if(!Number.isFinite(entry.createdAt)||now2<entry.createdAt||now2-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return null;let now2=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now2);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key2);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],status:"collecting",createdAt:now2};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now2=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now2);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="ready")return!0;return matches[0].status="ready",matches[0].readyAt=now2,!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint)=>({...fingerprint})),createdAt:generation.createdAt,readyAt:generation.readyAt,consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file2)=>declared.has(file2)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now2=Date.now()){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now2-session.lastToolCallTime>staleDurationMs)staleIds.push(id);for(let id of staleIds)swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id);return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now2=Date.now()){if(now2-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now2,sweepStaleSessions(staleDurationMs,now2)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now2=Date.now();sweepStaleSessions(staleDurationMs,now2);let sessionState={agentName,lastToolCallTime:now2,lastAgentEventTime:now2,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask: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,taskWorkflowCache:new Map,stageBCompletion:new Map,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID12(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,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,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now2)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals49.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals49.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){let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now2=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=now2,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;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.completionGateWarnedForTask)session.completionGateWarnedForTask=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.taskWorkflowCache)session.taskWorkflowCache=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.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID12();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;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.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now2,maybeSweepStaleSessions(),session}if(_internals49.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}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),newId=(session.lastInvocationIdByAgent[stripped]||0)+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now2=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now2,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now2,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key=`${stripped}:${newId}`;return session.windows[key]=window2,pruneOldWindows(sessionId,86400000,50),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 now2=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now2-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 ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.filter((file2)=>typeof file2==="string"&&file2.length>0))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file2){if(typeof file2!=="string"||file2.length===0)return!1;let existing=getModifiedFilesForTask(session,taskId);if(existing.includes(file2))return!0;return recordModifiedFilesForTask(session,taskId,[...existing,file2])}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides){let cache=ensureTaskWorkflowCache(session),existing=cache.get(taskId);cache.set(taskId,{generation:overrides.generation??existing?.generation??0,retryCount:overrides.retryCount??existing?.retryCount??0,lastOutcome:overrides.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides.updatedAt??existing?.updatedAt??""})}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=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState);if(currentIndex===-1||newIndex===-1||newIndex<=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>=LINEAR_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),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState==="complete")session.stageBCompletion?.delete(taskId),completeModifiedFilesForTask(session,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=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState);if(currentIndex===-1||newIndex===-1||newIndex<=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>=LINEAR_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"||newState==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState,options,councilConfig)}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),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}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.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,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"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence2){let snapshot=getTaskWorkflowSnapshot(evidence2);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path59.join(directory,".swarm","plan.json"),content=await fs35.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=path59.join(directory,".swarm","evidence"),entries=await fs35.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=path59.join(evidenceDir,entry.name),content=await fs35.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);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.taskWorkflowCache)session.taskWorkflowCache=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),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence2=evidenceMap.get(taskId);if(evidence2){let derivedWorkflow=evidenceToWorkflowState(evidence2);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence2]of evidenceMap){let council=evidence2.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence2);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);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 _internals49.buildRehydrationCache(directory),_internals49.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 setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map2=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map2.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;if(identity&&!liveContextIdentityMatches(cached2,identity))return;return cached2.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;return{modelID:cached2.modelID,providerID:cached2.providerID}}function evictOldestLiveContextWindow(map2,sessionID){if(map2.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map2=swarmState.lastBudgetBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{pct,tokens}),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}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 buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map2=swarmState.gateDenialCounts,existing=map2.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{count,directiveKey}),map2.size>MAX_TRACKED_GATE_DENIALS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.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,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals49;var init_state2=__esm(()=>{init_constants();init_plan_schema();init_schema();init_qa_gate_profile();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_session_start_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,LINEAR_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,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals49={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});function normalizeMessage(message){return message.replace(/\s+/g," ").trim().toLowerCase()}function pushAdvisory(session,message,opts){if(!message?.trim())return!1;if(session.pendingAdvisoryMessages??=[],opts?.dedupeKey){let key=opts.dedupeKey;if(session.pendingAdvisoryMessages.some((m)=>m.includes(key)))return!1}else if(session.pendingAdvisoryMessages.some((m)=>normalizeMessage(m)===normalizeMessage(message)))return!1;let cap=Math.max(1,opts?.maxPending??25);while(session.pendingAdvisoryMessages.length>=cap)session.pendingAdvisoryMessages.shift();return session.pendingAdvisoryMessages.push(message),!0}import{promises as fs36}from"node:fs";import path60 from"node:path";function isPathSafe2(targetPath,basePath){let resolvedTarget=path60.resolve(targetPath),resolvedBase=path60.resolve(basePath),rel=path60.relative(resolvedBase,resolvedTarget);return!rel.startsWith("..")&&!path60.isAbsolute(rel)}function isWithinReplaysDir(targetPath){let parts=path60.resolve(targetPath).split(path60.sep);for(let i=0;i<parts.length-1;i++)if(parts[i]===".swarm"&&parts[i+1]==="replays")return!0;return!1}function sanitizeFilename(input){return input.replace(/[^a-zA-Z0-9_-]/g,"_")}async function startReplayRecording(sessionID,directory){try{let replayDir=path60.join(directory,".swarm","replays"),filename=`${sanitizeFilename(sessionID)}-${Date.now()}.jsonl`,filepath=path60.join(replayDir,filename);if(!isPathSafe2(filepath,replayDir))return advisoryWarn(`[replay] Invalid path detected - path traversal attempt blocked for session ${sessionID}`),null;return await fs36.mkdir(replayDir,{recursive:!0}),filepath}catch(err){return log(`[replay] Failed to start recording for session ${sessionID}: ${err}`),null}}async function recordReplayEntry(artifactPath,sessionID,entry){try{if(!isWithinReplaysDir(artifactPath)){log(`[replay] Invalid artifact path - not within .swarm/replays/: ${artifactPath}`);return}let fullEntry={timestamp:new Date().toISOString(),sessionID,...entry},line=`${JSON.stringify(fullEntry)}
668
668
  `;await fs36.appendFile(artifactPath,line,"utf-8")}catch(err){log(`[replay] Failed to record entry: ${err}`)}}var init_replay=__esm(()=>{init_warning_buffer();init_logger()});function resetPrmSessionState(session,sessionId){if(session.prmEscalationTracker=void 0,session.prmInitialized=!1,session.prmPatternCounts=new Map,session.prmEscalationLevel=0,session.prmLastPatternDetected=null,session.prmHardStopPending=!1,session.prmHardStopInjectPending=!1,session.prmTrajectoryStep=0,session.prmInjectedAdvisoryKeys=new Set,session.prmStruckEpisodes=new Map,session.prmLadderCounts=new Map,session.replayArtifactPath=null,sessionId)_internals50.clearTrajectoryCache(sessionId)}function resolvePrmPatternPersistenceOptions(learning){return{enabled:learning.prm_persistence.enabled,min_support:learning.prm_persistence.min_support,cooldown_ms:learning.prm_persistence.cooldown_ms,admission_enabled:learning.realtime_admission.enabled,max_queue_size:learning.realtime_admission.max_queue_size}}function createPrmHook(config2,directory,patternPersistence){async function toolAfter(context){if(!config2.enabled)return;let{sessionID}=context,session=_internals50.getAgentSession(sessionID);if(!session||!session.delegationActive)return;try{let cachedTrajectory=_internals50.getInMemoryTrajectory(sessionID),trajectory=cachedTrajectory.length>0?cachedTrajectory:await _internals50.readTrajectory(sessionID,directory),detectionResult=_internals50.detectPatterns(trajectory,config2,session.prmTrajectoryStep);if(detectionResult.matches.length===0)return;session.prmStruckEpisodes??=new Map;let struckEpisodes=session.prmStruckEpisodes,strikeable=[],claimedThisTick=new Set;for(let match of[...detectionResult.matches].sort((a,b)=>a.stepRange[0]-b.stepRange[0])){if(claimedThisTick.has(match.pattern))continue;let episodeKey=`${match.pattern}|${match.stepRange[0]}`,struckAtCount=struckEpisodes.get(episodeKey);if(struckAtCount!==void 0){let threshold=resolvePatternThreshold(config2,match.pattern);if(match.occurrenceCount<struckAtCount+threshold)continue}claimedThisTick.add(match.pattern),strikeable.push(match)}if(strikeable.length===0){if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step;return}for(let match of strikeable){let episodeKey=`${match.pattern}|${match.stepRange[0]}`;struckEpisodes.delete(episodeKey),struckEpisodes.set(episodeKey,match.occurrenceCount)}while(struckEpisodes.size>MAX_TRACKED_EPISODES){let oldest=struckEpisodes.keys().next().value;if(oldest===void 0)break;struckEpisodes.delete(oldest)}if(patternPersistence?.enabled)for(let match of strikeable){let observation=_internals50.recordPatternObservation(sessionID,match,{minSupport:patternPersistence.min_support,cooldownMs:patternPersistence.cooldown_ms});if(observation.persistable&&observation.candidate){try{await _internals50.appendInsightCandidates(directory,[observation.candidate])}catch(err){warn(`[prm] insight-candidate append failed (non-fatal): ${err instanceof Error?err.message:String(err)}`)}if(patternPersistence.admission_enabled)_internals50.enqueueCandidate(sessionID,observation.candidate,{maxQueueSize:patternPersistence.max_queue_size})}}let sessionPrmState=session,escalationTracker=sessionPrmState.prmEscalationTracker;if(!sessionPrmState.replayArtifactPath)sessionPrmState.replayArtifactPath=await _internals50.startReplayRecording(sessionID,directory);let artifactPath=sessionPrmState.replayArtifactPath;if(!sessionPrmState.prmInitialized)sessionPrmState.prmInitialized=!0,_internals50.cleanupOldTrajectoryFiles(directory).catch(()=>{});if(!escalationTracker){let initialState=session.prmLastPatternDetected?{patternCounts:new Map(session.prmLadderCounts??[]),escalationLevel:session.prmEscalationLevel,lastPatternDetected:session.prmLastPatternDetected,hardStopPending:session.prmHardStopPending}:void 0;escalationTracker=new EscalationTracker(sessionID,initialState),sessionPrmState.prmEscalationTracker=escalationTracker}let previousEscalationLevel=session.prmEscalationLevel,tickHardStop=!1;for(let match of strikeable){let correction=_internals50.generateCourseCorrection(match,trajectory),formattedCorrection=_internals50.formatCourseCorrectionForInjection(correction),escalationLevel=0,hardStopPending=!1;if(config2.escalation_enabled!==!1){let escalationResult=escalationTracker.recordDetection(match);escalationLevel=escalationResult.level,hardStopPending=escalationResult.hardStop}let prmDedupeKey=`prm:${resolveLadderKey(match)}:${escalationLevel}`;if(!session.prmInjectedAdvisoryKeys?.has(prmDedupeKey))pushAdvisory(session,`[${prmDedupeKey}] ${formattedCorrection}`,{dedupeKey:prmDedupeKey}),session.prmInjectedAdvisoryKeys??=new Set,session.prmInjectedAdvisoryKeys.add(prmDedupeKey);if(session.prmPatternCounts.set(match.pattern,(session.prmPatternCounts.get(match.pattern)??0)+1),session.prmLadderCounts=escalationTracker.getLadderCounts(),session.prmEscalationLevel=escalationLevel,session.prmLastPatternDetected=match,tickHardStop=tickHardStop||hardStopPending,session.prmHardStopPending=tickHardStop,tickHardStop)session.prmHardStopInjectPending=!0;if(_internals50.telemetry.prmPatternDetected(sessionID,match.pattern,match.severity,match.category,match.stepRange),_internals50.telemetry.prmCourseCorrectionInjected(sessionID,match.pattern,escalationLevel),artifactPath)await _internals50.recordReplayEntry(artifactPath,sessionID,{type:"pattern_detected",data:{pattern:match.pattern,severity:match.severity,category:match.category,stepRange:match.stepRange,description:match.description,affectedAgents:match.affectedAgents,affectedTargets:match.affectedTargets,occurrenceCount:match.occurrenceCount}});if(artifactPath)await _internals50.recordReplayEntry(artifactPath,sessionID,{type:"course_correction",data:{pattern:correction.pattern,alert:correction.alert,category:correction.category,guidance:correction.guidance,action:correction.action,stepRange:correction.stepRange,escalationLevel}})}if(artifactPath&&session.prmEscalationLevel>previousEscalationLevel)await _internals50.recordReplayEntry(artifactPath,sessionID,{type:"escalation",data:{previousLevel:previousEscalationLevel,newLevel:session.prmEscalationLevel,hardStopPending:session.prmHardStopPending}});if(artifactPath&&session.prmHardStopPending&&previousEscalationLevel<3)await _internals50.recordReplayEntry(artifactPath,sessionID,{type:"hard_stop",data:{escalationLevel:session.prmEscalationLevel,triggeredAt:new Date().toISOString()}});if(trajectory.length>0)session.prmTrajectoryStep=trajectory[trajectory.length-1].step}catch(err){log(`[prm] toolAfter error for session ${sessionID}: ${err}`)}}return{toolAfter}}var _internals50,MAX_TRACKED_EPISODES=256;var init_prm=__esm(()=>{init_course_correction();init_escalation();init_pattern_detector();init_micro_reflector();init_candidate_queue();init_prm_pattern_support();init_state2();init_telemetry();init_logger();init_course_correction();init_escalation();init_pattern_detector();init_replay();init_trajectory_store();_internals50={getAgentSession,readTrajectory,getInMemoryTrajectory,detectPatterns,generateCourseCorrection,formatCourseCorrectionForInjection,cleanupOldTrajectoryFiles,clearTrajectoryCache,recordReplayEntry,startReplayRecording,telemetry,recordPatternObservation,enqueueCandidate,appendInsightCandidates}});function candidateSummary(resolution){let shown=resolution.candidates.slice(0,4).map((candidate)=>`${candidate.bindingId.slice(0,8)}/${candidate.generationId.slice(0,8)}@r${candidate.revision}`),omitted=Math.max(0,resolution.totalCandidates-shown.length);return`[${shown.join(", ")}${omitted>0?`, ... (+${omitted} more)`:""}]`}function formatScopeResolutionDiagnostic(input){let task=sanitizeDiagnosticText(input.taskId??"unknown",128),session=sanitizeDiagnosticText(input.sessionId,128);if(input.resolution.status==="ambiguous")return`SCOPE_BINDING_AMBIGUOUS: ${input.resolution.totalCandidates} exact live generations match task ${task} and session ${session}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`;if(input.resolution.status==="expired"){let lastExpiry=Math.max(...input.resolution.candidates.map((candidate)=>candidate.expiresAt)),expiredAt=Number.isFinite(lastExpiry)?new Date(lastExpiry).toISOString():"unknown";return`SCOPE_BINDING_EXPIRED: the exact generation for task ${task} and session ${session} expired while idle; expiredAt=${expiredAt}; candidates ${candidateSummary(input.resolution)}. ACTION[architect]: call declare_scope with replace_existing=true for this task/workspace, then dispatch a new Task call.`}if(input.resolution.status==="overloaded")return"SCOPE_BINDING_STORE_OVERLOADED: the complete live binding set exceeds the safe admission budget. ACTION[architect]: complete or expire terminal tasks, then retry declare_scope.";return null}var init_scope_resolution_diagnostic=__esm(()=>{init_path_identity()});var init_worktree=__esm(()=>{init_core3();init_merge()});var exports_worktree_provisioning_owner={};__export(exports_worktree_provisioning_owner,{scanWorktreeProvisioningOwnersForRecovery:()=>scanWorktreeProvisioningOwnersForRecovery,removeWorktreeProvisioningOwner:()=>removeWorktreeProvisioningOwner,recordWorktreeProvisioningOwner:()=>recordWorktreeProvisioningOwner,WORKTREE_PROVISIONING_OWNER_LEASE_MS:()=>WORKTREE_PROVISIONING_OWNER_LEASE_MS,WORKTREE_LIFECYCLE_LOCK_FILE:()=>WORKTREE_LIFECYCLE_LOCK_FILE});import{createHash as createHash23,randomBytes as randomBytes3}from"node:crypto";import*as fs37 from"node:fs";import*as path61 from"node:path";function ownerDirectory(directory){return path61.dirname(validateSwarmPath(directory,path61.join(PROVISIONING_OWNER_DIR,".containment-anchor")))}function ownerPath(directory,callID){let digest2=createHash23("sha256").update(callID).digest("hex");return validateSwarmPath(directory,path61.join(PROVISIONING_OWNER_DIR,`${digest2}.json`))}function isOwner(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,schemaVersion=candidate.schemaVersion,validTaskIdentity=schemaVersion===1?candidate.taskId===void 0:schemaVersion===2&&typeof candidate.taskId==="string"&&candidate.taskId.length>0&&candidate.taskId.length<=512;return(schemaVersion===1||schemaVersion===2)&&validTaskIdentity&&typeof candidate.callID==="string"&&candidate.callID.length>0&&candidate.callID.length<=512&&typeof candidate.parentSessionId==="string"&&candidate.parentSessionId.length>0&&candidate.parentSessionId.length<=512&&typeof candidate.worktreeSessionId==="string"&&candidate.worktreeSessionId.length>0&&candidate.worktreeSessionId.length<=512&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function recordWorktreeProvisioningOwner(directory,input){let owner={schemaVersion:input.taskId?2:1,callID:input.callID,parentSessionId:input.parentSessionId,worktreeSessionId:input.worktreeSessionId,...input.taskId?{taskId:input.taskId}:{},createdAt:Date.now()};if(!isOwner(owner))throw Error("invalid worktree provisioning owner");let absolutePath=ownerPath(directory,input.callID);fs37.mkdirSync(path61.dirname(absolutePath),{recursive:!0});let tempPath=`${absolutePath}.tmp-${randomBytes3(8).toString("hex")}`;try{fs37.writeFileSync(tempPath,`${JSON.stringify(owner)}
669
669
  `,{encoding:"utf8",flag:"wx"}),fs37.renameSync(tempPath,absolutePath)}catch(error49){try{fs37.unlinkSync(tempPath)}catch{}throw error49}return owner}function removeWorktreeProvisioningOwner(directory,callID){try{return fs37.unlinkSync(ownerPath(directory,callID)),!0}catch(error49){return error49.code==="ENOENT"}}function scanWorktreeProvisioningOwnersForRecovery(directory){let directoryPath,entries;try{directoryPath=ownerDirectory(directory),entries=fs37.readdirSync(directoryPath,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`worktree provisioning-owner directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_PROVISIONING_OWNERS)return{status:"uncertain",reason:`worktree provisioning-owner count exceeds the ${MAX_PROVISIONING_OWNERS}-marker safety bound`};let owners=[];for(let entry of entries){let absolutePath=path61.join(directoryPath,entry.name);try{if(fs37.statSync(absolutePath).size>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" exceeds the recovery size bound`};let raw=fs37.readFileSync(absolutePath,"utf8");if(Buffer.byteLength(raw,"utf8")>MAX_PROVISIONING_OWNER_BYTES)return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" changed beyond the recovery size bound`};let parsed=JSON.parse(raw);if(!isOwner(parsed))return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is invalid`};owners.push(parsed)}catch(error49){return{status:"uncertain",reason:`worktree provisioning owner "${entry.name}" is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}return{status:"ok",owners}}var PROVISIONING_OWNER_DIR="worktree-provisioning-owners",MAX_PROVISIONING_OWNERS=512,MAX_PROVISIONING_OWNER_BYTES=16384,WORKTREE_PROVISIONING_OWNER_LEASE_MS=300000,WORKTREE_LIFECYCLE_LOCK_FILE=".swarm/locks/init-orphan-recovery.lock";var init_worktree_provisioning_owner=__esm(()=>{init_utils2()});import*as fs38 from"node:fs";import*as path62 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs38.statSync(path62.join(directory,".git"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error49 instanceof Error?error49.message:String(error49)}`}}let proc=bunSpawn(["git","-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});try{let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error49){return{status:"uncertain",reason:`ownership tag scan failed: ${error49 instanceof Error?error49.message:String(error49)}`}}finally{try{proc.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals51});import*as fs39 from"node:fs";import*as path63 from"node:path";function normalizedPath(value){let resolved=path63.normalize(path63.resolve(value));return process.platform==="win32"?resolved.toLowerCase():resolved}function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=normalizedPath(descriptor.worktreePath)===normalizedPath(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record2){let settlement=record2.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record2,identity,ownerKind){if(!record2.worktree)return null;let coordinates=descriptorCoordinateMatch(record2.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record2))return null;let lifecycle=record2.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record2.correlationId} is ${record2.status}`+(record2.coderSettlement?` with coder settlement ${record2.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now2=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now2-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals51.statSync(identity.worktreePath)}catch(error49){let code=error49.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`};if(!_internals51.removeWorktreeProvisioningOwner(identity.directory,owner.callID))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record2 of primary.owners){let classified=classifyRecord(record2,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&normalizedPath(failure.worktreePath)===normalizedPath(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals51;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals51={statSync:fs39.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals52,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash24}from"node:crypto";import*as fs40 from"node:fs/promises";import*as path64 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path64.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record2 of awaitingMergeByCallID.values())if(record2.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw Error(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw Error(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),Error(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),serializationStateBySessionID.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config2){let state=serializationStateBySessionID.get(sessionID);if(!state)return;let count=config2.serialization_release_after_dispatches??5,ttl=config2.serialization_release_after_ms??60000;if(state.successfulDispatchesSince>=count){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key)){standardWorktreeSerializationSessions.delete(key),serializationStateBySessionID.delete(key),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc=_internals52.bunSpawn(["git","-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS}),stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
670
670
  `)){let line=rawLine.trim();if(line.startsWith("worktree ")){if(current.path)entries.push(current);current={path:line.slice(9),branch:void 0,prunable:!1}}else if(line.startsWith("branch "))current.branch=line.slice(7);else if(line==="prunable"||line.startsWith("prunable "))current.prunable=!0}if(current.path)entries.push(current);for(let entry of entries){if(!entry.branch)continue;if(entry.prunable)continue;let branchName=entry.branch.startsWith("refs/heads/")?entry.branch.slice(11):entry.branch,segments=branchName.split("/");if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane"){if(segments[3]===taskId){let ownerSessionId=segments[2];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}if(segments.length>=3&&segments[0]==="swarm-lane"){if(segments[2]===taskId){let ownerSessionId=segments[1];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}}return{collision:!1}}function isLaneOwnedByCurrentSession(branchName,expectedSessionId){return _internals47.extractSessionId(branchName)===expectedSessionId}async function inspectStandardWorktreeCollisionOwnership2(identity){return(await Promise.resolve().then(() => (init_worktree_collision_ownership(),exports_worktree_collision_ownership))).inspectStandardWorktreeCollisionOwnership(identity)}async function precreateStandardWorktreeSession(args2){let worktreeConfig=resolveWorktreeIsolationConfig(args2.config);if(worktreeConfig.policy==="disabled")return;if(standardWorktreeSerializationSessions.has(args2.parentSessionID)){if(checkStandardWorktreeSerializationRelease(args2.parentSessionID,worktreeConfig),!standardWorktreeSerializationSessions.has(args2.parentSessionID))return}if(!hasStandardWorktreeDispatchCapacity()){if(worktreeConfig.policy==="required")throw Error("STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");serializeStandardWorktreeDispatches(args2.parentSessionID,"STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");return}let client=swarmState.opencodeClient;if(!client){handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,"STANDARD_WORKTREE_ISOLATION_UNAVAILABLE: OpenCode SDK client is unavailable; standard parallel coder work cannot be isolated.");return}let laneIndex=allocateStandardLaneIndex(args2.parentSessionID),lifecycleLock=await _internals52.tryAcquireWorktreeLifecycleLock(args2.directory,WORKTREE_LIFECYCLE_LOCK_FILE,"worktree-provisioning",args2.taskId);if(!lifecycleLock.acquired)hardStopStandardWorktreeLifecycle(args2.parentSessionID,"STANDARD_WORKTREE_LIFECYCLE_BUSY: init orphan recovery is active; retry this coder dispatch after recovery completes.");try{let collision=await _internals52.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(collision.uncertainty)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);if(collision.collision){if(!collision.existingBranch||!collision.worktreePath||!isLaneOwnedByCurrentSession(collision.existingBranch,args2.parentSessionID)){let ownerInfo=collision.ownerSessionId?` owned by session ${collision.ownerSessionId}`:" with uncertain ownership";hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION: task ${args2.taskId} already has a lane on branch ${collision.existingBranch??"unknown"}${ownerInfo}; cleanup and provisioning were blocked.`)}for(let dispatch of _internals52.standardWorktreeByCallID.values())if(dispatch.handle.branchName===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);for(let record2 of _internals52.awaitingMergeByCallID.values())if(record2.branch===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);let ownership=await _internals52.inspectStandardWorktreeCollisionOwnership({directory:args2.directory,parentSessionId:args2.parentSessionID,taskId:args2.taskId,branchName:collision.existingBranch,worktreePath:collision.worktreePath});if(ownership.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNERSHIP_UNCERTAIN: ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);if(ownership.status==="protected")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PROTECTED: ${ownership.ownerKind} owner is ${ownership.lifecycle}; ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);let collisionPathExists=!0;try{await fs40.stat(collision.worktreePath)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENOTDIR")collisionPathExists=!1;else hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PATH_STAT_FAILED: ${error49 instanceof Error?error49.message:String(error49)}. Destructive cleanup and provisioning were blocked.`)}if(collisionPathExists){let preserveResult=await _internals52.preserveDirtyWorktreeAtPath(collision.worktreePath,collision.existingBranch,"denied",args2.directory,worktreeConfig.worktree_dir);if(preserveResult.outcome==="preserve-failed")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args2.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);let removeResult=await _internals52.removeWorktree(collision.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir});if("error"in removeResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);let cleanupResult=await _internals52.postMergeCleanup(args2.directory,collision.existingBranch);if("error"in cleanupResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`)}else{let pruneResult=await _internals52.pruneStaleWorktreeMetadata(args2.directory);if("error"in pruneResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`)}let verification=await _internals52.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(verification.uncertainty||verification.collision)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty??"git still reports the colliding lane after cleanup"}. Provisioning was blocked.`)}_internals52.recordWorktreeProvisioningOwner(args2.directory,{callID:args2.callID,parentSessionId:args2.parentSessionID,worktreeSessionId:args2.parentSessionID,taskId:args2.taskId})}catch(error49){if(error49 instanceof Error&&(error49.message.startsWith("STANDARD_WORKTREE_")||error49.message.startsWith("PREPROVISION_COLLISION")))throw error49;hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PERSIST_FAILED: ${error49 instanceof Error?error49.message:String(error49)}.`)}finally{try{await lifecycleLock.lock._release?.()}catch{}}let provisionResult;try{provisionResult=await _internals52.provisionWorktree(args2.directory,args2.taskId,args2.parentSessionID,{purpose:"lane",worktreeDir:worktreeConfig.worktree_dir,mergeStrategy:worktreeConfig.merge_strategy,depsStrategy:worktreeConfig.deps_strategy,scope:args2.scope})}catch(error49){throw _internals52.removeWorktreeProvisioningOwner(args2.directory,args2.callID),error49}if("error"in provisionResult){_internals52.removeWorktreeProvisioningOwner(args2.directory,args2.callID);let message=`STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}let originalPrompt=typeof args2.outputArgs.prompt==="string"?args2.outputArgs.prompt:"";args2.outputArgs.prompt=["<worktree_lane_context>",`authoritative_lane_root: ${JSON.stringify(provisionResult.worktreePath)}`,"All FILE declarations and scope-bound edit/write paths must be workspace-relative to authoritative_lane_root.","Do not declare project-root absolute paths; resolve and operate inside this lane root.","</worktree_lane_context>","",originalPrompt].join(`
@@ -1696,7 +1696,7 @@ ${inv.staleActiveSkills.slice(0,10).map((s)=>`- ${s.slug} | ${s.reasons.join(",
1696
1696
  This project was already finalized in a previous /swarm close run. The plan has been archived and cleaned up. No further action is needed.`}}catch{}}let phases=planData.phases??[],inProgressPhases=phases.filter((p)=>p.status==="in_progress"),isForced=args2.includes("--force"),runSkillReview=args2.includes("--skill-review"),planAlreadyDone=!1;if(planExists)planAlreadyDone=phases.length>0&&phases.every((p)=>p.status==="complete"||p.status==="completed"||p.status==="blocked"||p.status==="closed");let{config:loadedConfig}=_internals88.loadPluginConfigWithMeta(directory),config3=KnowledgeConfigSchema.parse(loadedConfig.knowledge??{}),ctx={directory,swarmDir,planData,planExists,planAlreadyDone,config:config3,projectName:planData.title??"Unknown Project",warnings:[],closedPhases:[],closedTasks:[],sessionStart:void 0,isForced,runSkillReview,options,phases,inProgressPhases,curationSucceeded:!1,curationResult:void 0,allLessons:[],explicitLessons:[],retroLessons:[],knowledgeSkillHint:"",skillReviewSummary:"",postMortemSummary:"",sessionReflection:void 0,hivePromoted:0,sessionKnowledgeCreated:0,fallbackKnowledgeCreated:0,dedupDropped:0,dedupAvailable:!0,retroLessonTotal:0,fullAuto:!1,originalStatuses:new Map,guaranteeResult:{closedPhaseIds:[],closedTaskIds:[]},archiveResult:"",archivedFileCount:0,archivedActiveStateFiles:new Set,archivedActiveStateDirs:new Set,archiveFailureReasons:new Map,archiveResults:[],archiveStageFailed:!1,timestamp:"",archiveDir:"",archiveSuffix:"",args:args2};if(ctx.fullAuto=options.sessionID?_internals88.detectFullAuto(directory,options.sessionID):!1,await runFinalizeStage(ctx),ctx.terminalizationError)return`❌ Close paused before reward, archive, cleanup, teardown, and Git alignment because terminal plan/evidence reconciliation failed: ${ctx.terminalizationError}
1697
1697
 
1698
1698
  No active state was archived or removed. Fix the reported durable-state problem, then retry /swarm close.`;await _internals88.runFinalizeRewardSweep({directory,closedTaskIds:ctx.guaranteeResult.closedTaskIds,memoryConfig:loadedConfig.memory}),await runArchiveStage(ctx);let cleanResult=await runCleanStage(ctx);emitCloseArchiveResult(ctx,cleanResult);let{gitAlignResult,prunedBranches}=await runAlignStage(ctx),closeSummaryPath=validateSwarmPath(ctx.directory,"close-summary.md"),finalizationType=ctx.isForced?"Forced closure":ctx.planAlreadyDone?"Plan already terminal — cleanup only":"Normal finalization",summaryContent=["# Swarm Close Summary","",`**Project:** ${ctx.projectName}`,`**Closed:** ${new Date().toISOString()}`,`**Finalization:** ${finalizationType}`,"","## Retrospective",!ctx.planExists?"_No plan — ad-hoc session_":ctx.closedPhases.length>0?ctx.closedPhases.map((id)=>`- Phase ${id} closed`).join(`
1699
- `):"_No phases closed this run_",...ctx.closedTasks.length>0?["",`**Tasks marked closed:** ${ctx.closedTasks.length}`,...ctx.closedTasks.map((id)=>`- ${id}`)]:[],"","## Lessons Committed",ctx.allLessons.length>0?"| # | Lesson |":"_No lessons committed_",...ctx.allLessons.length>0?["| --- | --- |",...ctx.allLessons.map((l,i)=>`| ${i+1} | ${l} |`)]:[],...ctx.knowledgeSkillHint?["",ctx.knowledgeSkillHint]:[],...ctx.runSkillReview?["","## Skill Review",ctx.skillReviewSummary||"Skill review completed without details."]:[],...ctx.sessionReflection?["",`## Session Reflection (${ctx.sessionReflection.source})`,"",ctx.sessionReflection.architectReport]:[],"","## Local Repo State",...gitAlignResult?[`- **Git:** ${gitAlignResult}`]:["- Git alignment skipped"],...prunedBranches.length>0?[`- **Pruned branches:** ${prunedBranches.join(", ")}`]:[],`- **Archive:** ${ctx.archiveResult}`,...cleanResult.cleanedFiles.length>0?[`- **Cleaned:** ${cleanResult.cleanedFiles.length} file(s)`]:[],"","## Context","- Reset context.md for next session","- Cleared agent sessions and delegation chains",...cleanResult.configBackupsRemoved>0?[`- Removed ${cleanResult.configBackupsRemoved} stale config backup file(s)`]:[],...cleanResult.swarmPlanFilesRemoved>0?[`- Removed ${cleanResult.swarmPlanFilesRemoved} SWARM_PLAN checkpoint artifact(s) from .swarm/plan-export/ and legacy locations`]:[],...ctx.planExists&&!ctx.planAlreadyDone?["- Set non-completed phases/tasks to closed status"]:[],...ctx.curationSucceeded&&ctx.allLessons.length>0?[`- Committed ${ctx.allLessons.length} lesson(s) to knowledge store`]:[],...ctx.hivePromoted>0?[`- Promoted ${ctx.hivePromoted} lesson(s) to hive knowledge`]:[],"",...ctx.warnings.length>0?["## Warnings",...ctx.warnings.map((w)=>`- ${w}`),""]:[]].join(`
1699
+ `):"_No phases closed this run_",...ctx.closedTasks.length>0?["",`**Tasks marked closed:** ${ctx.closedTasks.length}`,...ctx.closedTasks.map((id)=>`- ${id}`)]:[],"","## Lessons Committed",ctx.allLessons.length>0?"| # | Lesson |":"_No lessons committed_",...ctx.allLessons.length>0?["| --- | --- |",...ctx.allLessons.map((l,i)=>`| ${i+1} | ${l} |`)]:[],...ctx.knowledgeSkillHint?["",ctx.knowledgeSkillHint]:[],...ctx.runSkillReview?["","## Skill Review",ctx.skillReviewSummary||"Skill review completed without details."]:[],...ctx.sessionReflection?["",`## Session Reflection (${ctx.sessionReflection.source})`,"",ctx.sessionReflection.architectReport]:[],"","## Local Repo State",...gitAlignResult?[`- **Git:** ${gitAlignResult}`]:["- Git alignment skipped"],...prunedBranches.length>0?[`- **Pruned branches:** ${prunedBranches.join(", ")}`]:[],`- **Archive:** ${ctx.archiveResult}`,...cleanResult.cleanedFiles.length>0?[`- **Cleaned:** ${cleanResult.cleanedFiles.length} file(s)`]:[],"","## Context","- Reset context.md for next session","- Cleared agent sessions, delegation chains, and active-agent mappings",...cleanResult.configBackupsRemoved>0?[`- Removed ${cleanResult.configBackupsRemoved} stale config backup file(s)`]:[],...cleanResult.swarmPlanFilesRemoved>0?[`- Removed ${cleanResult.swarmPlanFilesRemoved} SWARM_PLAN checkpoint artifact(s) from .swarm/plan-export/ and legacy locations`]:[],...ctx.planExists&&!ctx.planAlreadyDone?["- Set non-completed phases/tasks to closed status"]:[],...ctx.curationSucceeded&&ctx.allLessons.length>0?[`- Committed ${ctx.allLessons.length} lesson(s) to knowledge store`]:[],...ctx.hivePromoted>0?[`- Promoted ${ctx.hivePromoted} lesson(s) to hive knowledge`]:[],"",...ctx.warnings.length>0?["## Warnings",...ctx.warnings.map((w)=>`- ${w}`),""]:[]].join(`
1700
1700
  `),closeSummaryTempPath=path117.join(path117.dirname(closeSummaryPath),`${path117.basename(closeSummaryPath)}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`);try{await fs58.writeFile(closeSummaryTempPath,summaryContent,"utf-8"),fsSync10.renameSync(closeSummaryTempPath,closeSummaryPath),invalidateCachedArtifact(closeSummaryPath)}catch(error93){try{fsSync10.unlinkSync(closeSummaryTempPath)}catch{}let msg=error93 instanceof Error?error93.message:String(error93);ctx.warnings.push(`Failed to write close-summary.md: ${msg}`),log("[close-command] Failed to write close-summary.md:",error93)}try{let sessionIdsToEnd=[...swarmState.agentSessions.keys()];for(let sessionId of sessionIdsToEnd)_internals88.endAgentSession(sessionId);_internals88.resetSwarmStatePreservingSingletons()}catch(teardownError){let msg=teardownError instanceof Error?teardownError.message:String(teardownError);ctx.warnings.push(`Session teardown encountered an error after finalization completed (state may not be fully reset): ${msg}`),log("[close-command] teardown error:",teardownError)}let retroWarnings=ctx.warnings.filter((w)=>w.includes("Retrospective write")||w.includes("retrospective write")||w.includes("Session retrospective")),otherWarnings=ctx.warnings.filter((w)=>!w.includes("Retrospective write")&&!w.includes("retrospective write")&&!w.includes("Session retrospective")),warningMsg="";if(retroWarnings.length>0)warningMsg+=`
1701
1701
 
1702
1702
  **⚠ Retrospective evidence incomplete:**
@@ -2175,7 +2175,7 @@ Actionability (direct text only; required unless knowledge.promotion_require_act
2175
2175
  `)}
2176
2176
  `,"utf-8"),invalidateCachedArtifact(filePath)}catch{}}function deriveAction(tool3){let toolLower=normalizeToolNameLowerCase(tool3??"");if(toolLower==="task")return"delegate";if(["write","edit","apply_patch","swarm_apply_patch"].includes(toolLower))return"edit";if(["read","glob","grep","search"].includes(toolLower))return"read";if(["bash","shell"].includes(toolLower))return"execute";if(toolLower==="test_runner")return"test";return"tool_use"}function fnv1aHex(text){let hash4=2166136261;for(let i=0;i<text.length;i++)hash4^=text.charCodeAt(i),hash4=Math.imul(hash4,16777619)>>>0;return hash4.toString(16).padStart(8,"0")}function redactCommandSecrets(text){let redacted=redactSecrets(text).replace(URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@"),beginMarker=redacted.search(/-----BEGIN [A-Z ]*PRIVATE KEY-----/);return beginMarker===-1?redacted:`${redacted.slice(0,beginMarker)}[REDACTED:private_key_block]`}function normalizeCommandTarget(command){let normalized=command.trim().replace(/\s+/g," "),bounded=normalized.length>MAX_COMMAND_TARGET_LENGTH?`${normalized.slice(0,MAX_COMMAND_TARGET_LENGTH-3)}...`:normalized,redacted=redactCommandSecrets(bounded);if(redacted===bounded)return redacted;let prefix=`#${fnv1aHex(bounded)} `,room=MAX_COMMAND_TARGET_LENGTH-prefix.length,body=redacted.length>room?`${redacted.slice(0,room-3)}...`:redacted;return`${prefix}${body}`}function extractTarget(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let subagentType=args2.subagent_type;if(typeof subagentType==="string"&&subagentType.length>0)return subagentType}let targetFields=["filePath","path","file","target"];for(let field of targetFields){let value=args2[field];if(typeof value==="string"&&value.length>0)return value}let toolLower=tool3.toLowerCase();if(toolLower==="bash"||toolLower==="shell"||toolLower==="execute"||toolLower==="command"){let command=args2.command;if(typeof command==="string"&&command.trim().length>0)return normalizeCommandTarget(command);let description=args2.description;if(typeof description==="string"&&description.length>0){let safeDescription=redactCommandSecrets(description.slice(0,REDACTION_SCAN_WINDOW));return safeDescription.length>30?`${safeDescription.slice(0,27)}...`:safeDescription}let argsStr=args2.args;if(typeof argsStr==="string"&&argsStr.trim().length>0)return normalizeCommandTarget(argsStr)}return""}function extractIntent(tool3,args2){if(!args2)return"";if(tool3.toLowerCase()==="task"){let{prompt,description}=args2,safeText=redactCommandSecrets((typeof prompt==="string"?prompt:typeof description==="string"?description:"").slice(0,REDACTION_SCAN_WINDOW));if(safeText.length>100)return`${safeText.slice(0,97)}...`;return safeText}let intentFields=["description","task"];for(let field of intentFields){let value=args2[field];if(typeof value==="string"&&value.length>0){let safe=redactCommandSecrets(value.slice(0,REDACTION_SCAN_WINDOW));return safe.length>200?`${safe.slice(0,197)}...`:safe}}return""}function mapResult(verdict){if(verdict==="success")return"success";if(verdict==="failure")return"failure";return"pending"}function createTrajectoryLoggerHook(config3,_directory){let enabled=config3.enabled??!0,maxLines=config3.max_lines??500;return{toolAfter:async(input,output)=>{if(!enabled)return;let sessionId=input.sessionID;if(consumeDeniedCallMarker(sessionId,input.callID)){callStartTimes.delete(`${sessionId}:${input.callID}`);return}let session=swarmState.agentSessions.get(sessionId);if(!session?.delegationActive)return;let taskId=session.currentTaskId;if(!taskId)return;let startKey=`${sessionId}:${input.callID}`,startTime=callStartTimes.get(startKey)??Date.now();callStartTimes.delete(startKey);let elapsed_ms=Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionId)??session?.agentName??"unknown",args_summary=summarizeArgs(input.args,200),verdict=deriveVerdict(output),step=nextTrajectoryStep(sessionId),action=deriveAction(input.tool),target=extractTarget(input.tool,input.args),intent=extractIntent(input.tool,input.args),result=mapResult(verdict),entry={step,agent:agentName,action,target,intent,timestamp:new Date().toISOString(),result,tool:input.tool,args_summary,verdict,elapsed_ms},sanitized=sanitizeTaskId2(taskId),relativePath2=path168.join("evidence",sanitized,"trajectory.jsonl"),trajectoryPath=validateSwarmPath(_directory,relativePath2);try{await fs90.mkdir(path168.dirname(trajectoryPath),{recursive:!0});let line=`${JSON.stringify(entry)}
2177
2177
  `;await fs90.appendFile(trajectoryPath,line,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}try{await appendTrajectoryEntry(sessionId,entry,_directory,maxLines)}catch{}}}}function markDeniedCall(sessionId,callID){if(!callID)return;let now2=Date.now();for(let[key2,expiresAt]of deniedCallMarkers)if(expiresAt<=now2)deniedCallMarkers.delete(key2);let key=`${sessionId}:${callID}`;deniedCallMarkers.delete(key),deniedCallMarkers.set(key,now2+DENIED_CALL_TTL_MS);while(deniedCallMarkers.size>MAX_DENIED_CALL_MARKERS){let oldest=deniedCallMarkers.keys().next().value;if(oldest===void 0||oldest===key)break;deniedCallMarkers.delete(oldest)}}function consumeDeniedCallMarker(sessionId,callID){if(!callID)return!1;let key=`${sessionId}:${callID}`,expiresAt=deniedCallMarkers.get(key);if(expiresAt===void 0)return!1;return deniedCallMarkers.delete(key),expiresAt>Date.now()}async function recordDeniedToolCall(sessionID,input,errorMessage2,directory,options){try{let session=swarmState.agentSessions.get(sessionID);if(!session?.delegationActive)return;let maxLines=options?.maxLines??500,startKey=`${sessionID}:${input.callID}`,startTime=callStartTimes.get(startKey);if(startTime!==void 0)callStartTimes.delete(startKey);let elapsed_ms=startTime===void 0?0:Date.now()-startTime,agentName=swarmState.activeAgent.get(sessionID)??session.agentName??"unknown",code=deriveGateDenialCode(errorMessage2),entry={step:nextTrajectoryStep(sessionID),agent:agentName,action:deriveAction(input.tool),target:extractTarget(input.tool,input.args),intent:`denied: ${code}`,timestamp:new Date().toISOString(),result:"failure",tool:input.tool,args_summary:summarizeArgs(input.args,200),verdict:"failure",elapsed_ms,callID:input.callID};markDeniedCall(sessionID,input.callID);try{await appendTrajectoryEntry(sessionID,entry,directory,maxLines)}catch{}let taskId=session.currentTaskId;if(!taskId)return;try{let relativePath2=path168.join("evidence",sanitizeTaskId2(taskId),"trajectory.jsonl"),trajectoryPath=validateSwarmPath(directory,relativePath2);await fs90.mkdir(path168.dirname(trajectoryPath),{recursive:!0}),await fs90.appendFile(trajectoryPath,`${JSON.stringify(entry)}
2178
- `,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}}catch{}}function clearTrajectoryStep(sessionId){clearTrajectoryStepCounters(sessionId)}function summarizeArgs(args2,maxLength){if(!args2||Object.keys(args2).length===0)return"";let summaries=[];for(let[key,value]of Object.entries(args2)){if(SENSITIVE_FIELDS.has(key)||isSensitiveKey(key)){summaries.push(`${key}:[REDACTED]`);continue}if(value===null||value===void 0)summaries.push(`${key}:null`);else if(typeof value==="string"){let window2=value.slice(0,REDACTION_SCAN_WINDOW),redacted=redactCommandSecrets(window2),truncated=redacted.length>50?`${redacted.slice(0,50)}...`:redacted;summaries.push(`${key}:"${truncated}"`)}else if(typeof value==="number"||typeof value==="boolean")summaries.push(`${key}:${String(value)}`);else if(Array.isArray(value)){let itemSummary=value.length>3?`${value.slice(0,3).map(String).join(",")},...(+${value.length-3})`:value.map(String).join(",");summaries.push(`${key}:[${itemSummary}]`)}else if(typeof value==="object"){let keys=Object.keys(value);summaries.push(`${key}:{${keys.join(",")}}`)}else summaries.push(`${key}:${typeof value}`)}let summary=summaries.join(" ");return summary.length>maxLength?`${summary.slice(0,maxLength-3)}...`:summary}function deriveVerdict(output){if(output.metadata&&typeof output.metadata==="object"&&!Array.isArray(output.metadata)){let meta3=output.metadata;if(typeof meta3.verdict==="string"&&meta3.verdict.length>0)return meta3.verdict;if(meta3.success===!1||meta3.passed===!1)return"failure";if(meta3.success===!0||meta3.passed===!0)return"success"}let outputStr=String(output.output??"");if(outputStr.startsWith("Error:")||outputStr.startsWith("error:")||outputStr.startsWith("Error: "))return"failure";return"success"}var callStartTimes,SENSITIVE_FIELDS,SENSITIVE_SUBSTRINGS,URL_CREDENTIALS_PATTERN,REDACTION_SCAN_WINDOW=4096,MAX_COMMAND_TARGET_LENGTH=200,MAX_DENIED_CALL_MARKERS=500,DENIED_CALL_TTL_MS=300000,deniedCallMarkers;var init_trajectory_logger=__esm(()=>{init_manager2();init_redaction();init_trajectory_store();init_state2();init_swarm_artifact_cache();init_gate_denial_tracker();init_normalize_tool_name();init_trajectory_step_state();init_utils2();callStartTimes=new Map,SENSITIVE_FIELDS=new Set(["password","token","secret","api_key","apikey","authorization","access_token","refresh_token","private_key","secret_key","credential","auth","bearer","x-api-key","session_id","cookie"]),SENSITIVE_SUBSTRINGS=["key","secret","token","password","auth","credential","private","certificate","bearer","session","cookie"];URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g;deniedCallMarkers=new Map});import*as fs91 from"node:fs";import*as path169 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function handleResetSessionCommand(directory,_args){let results=[];try{let backup=_internals132.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path169.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let statePath;try{if(statePath=validateSwarmPath(directory,"session/state.json"),fs91.existsSync(statePath))fs91.unlinkSync(statePath),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{results.push("❌ Failed to delete state.json")}let sessionDir=statePath?path169.dirname(statePath):void 0,sessionFiles=[];if(sessionDir&&fs91.existsSync(sessionDir))try{sessionFiles=fs91.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json")continue;let filePath=path169.join(sessionDir,file3);try{if(!fs91.existsSync(filePath))continue;if(!fs91.lstatSync(filePath).isFile())continue;fs91.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);swarmState.agentSessions.clear(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`);let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let worktreesDir=path169.resolve(path169.dirname(directory),SWARM_WORKTREE_DIR_NAME);try{if(fs91.existsSync(worktreesDir))fs91.rmSync(worktreesDir,{recursive:!0,force:!0}),results.push("✅ Removed .swarm-worktrees/ directory")}catch(err){results.push(`⚠️ Failed to remove .swarm-worktrees/: ${errorMessage2(err)}`)}try{let branchResult=await _internals132.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","**All circuit breakers and revision limits have been cleared.** You can continue in this session — fresh state will be initialized automatically on the next tool call."].join(`
2178
+ `,"utf-8"),await truncateTrajectoryFile(trajectoryPath,maxLines)}catch{}}catch{}}function clearTrajectoryStep(sessionId){clearTrajectoryStepCounters(sessionId)}function summarizeArgs(args2,maxLength){if(!args2||Object.keys(args2).length===0)return"";let summaries=[];for(let[key,value]of Object.entries(args2)){if(SENSITIVE_FIELDS.has(key)||isSensitiveKey(key)){summaries.push(`${key}:[REDACTED]`);continue}if(value===null||value===void 0)summaries.push(`${key}:null`);else if(typeof value==="string"){let window2=value.slice(0,REDACTION_SCAN_WINDOW),redacted=redactCommandSecrets(window2),truncated=redacted.length>50?`${redacted.slice(0,50)}...`:redacted;summaries.push(`${key}:"${truncated}"`)}else if(typeof value==="number"||typeof value==="boolean")summaries.push(`${key}:${String(value)}`);else if(Array.isArray(value)){let itemSummary=value.length>3?`${value.slice(0,3).map(String).join(",")},...(+${value.length-3})`:value.map(String).join(",");summaries.push(`${key}:[${itemSummary}]`)}else if(typeof value==="object"){let keys=Object.keys(value);summaries.push(`${key}:{${keys.join(",")}}`)}else summaries.push(`${key}:${typeof value}`)}let summary=summaries.join(" ");return summary.length>maxLength?`${summary.slice(0,maxLength-3)}...`:summary}function deriveVerdict(output){if(output.metadata&&typeof output.metadata==="object"&&!Array.isArray(output.metadata)){let meta3=output.metadata;if(typeof meta3.verdict==="string"&&meta3.verdict.length>0)return meta3.verdict;if(meta3.success===!1||meta3.passed===!1)return"failure";if(meta3.success===!0||meta3.passed===!0)return"success"}let outputStr=String(output.output??"");if(outputStr.startsWith("Error:")||outputStr.startsWith("error:")||outputStr.startsWith("Error: "))return"failure";return"success"}var callStartTimes,SENSITIVE_FIELDS,SENSITIVE_SUBSTRINGS,URL_CREDENTIALS_PATTERN,REDACTION_SCAN_WINDOW=4096,MAX_COMMAND_TARGET_LENGTH=200,MAX_DENIED_CALL_MARKERS=500,DENIED_CALL_TTL_MS=300000,deniedCallMarkers;var init_trajectory_logger=__esm(()=>{init_manager2();init_redaction();init_trajectory_store();init_state2();init_swarm_artifact_cache();init_gate_denial_tracker();init_normalize_tool_name();init_trajectory_step_state();init_utils2();callStartTimes=new Map,SENSITIVE_FIELDS=new Set(["password","token","secret","api_key","apikey","authorization","access_token","refresh_token","private_key","secret_key","credential","auth","bearer","x-api-key","session_id","cookie"]),SENSITIVE_SUBSTRINGS=["key","secret","token","password","auth","credential","private","certificate","bearer","session","cookie"];URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g;deniedCallMarkers=new Map});import*as fs91 from"node:fs";import*as path169 from"node:path";function errorMessage2(err){if(err instanceof Error)return err.message;return String(err)}async function handleResetSessionCommand(directory,_args){let results=[];try{let backup=_internals132.backupSwarmStateBeforeReset(directory,"reset-session",["session"]);if(backup.backupDir&&backup.copied.length>0){let rel=path169.relative(directory,backup.backupDir);results.push(`\uD83D\uDCE6 Backed up session state to ${rel}/ (restore by copying files back into .swarm/session/)`)}for(let w of backup.warnings)results.push(`⚠️ Backup warning: ${w}`)}catch(err){results.push(`⚠️ Auto-backup failed (continuing with reset): ${err instanceof Error?err.message:String(err)}`)}let statePath;try{if(statePath=validateSwarmPath(directory,"session/state.json"),fs91.existsSync(statePath))fs91.unlinkSync(statePath),results.push("✅ Deleted .swarm/session/state.json");else results.push("⏭️ state.json not found (already clean)")}catch{results.push("❌ Failed to delete state.json")}let sessionDir=statePath?path169.dirname(statePath):void 0,sessionFiles=[];if(sessionDir&&fs91.existsSync(sessionDir))try{sessionFiles=fs91.readdirSync(sessionDir)}catch(err){results.push(`❌ Failed to read session directory: ${errorMessage2(err)}`)}for(let file3 of sessionFiles){if(file3==="state.json")continue;let filePath=path169.join(sessionDir,file3);try{if(!fs91.existsSync(filePath))continue;if(!fs91.lstatSync(filePath).isFile())continue;fs91.unlinkSync(filePath),results.push(`✓ Deleted ${file3}`)}catch(err){results.push(`❌ Failed to delete ${file3}: ${errorMessage2(err)}`)}}let sessionCount=swarmState.agentSessions.size;for(let[sessionId,session]of swarmState.agentSessions)resetPrmSessionState(session,sessionId),clearTrajectoryStep(sessionId);swarmState.agentSessions.clear(),results.push(`✅ Cleared ${sessionCount} in-memory agent session(s)`);let chainCount=swarmState.delegationChains.size;swarmState.delegationChains.clear(),results.push(`✅ Cleared ${chainCount} delegation chain(s)`);let activeAgentCount=swarmState.activeAgent.size;swarmState.activeAgent.clear(),results.push(`✅ Cleared ${activeAgentCount} active-agent mapping(s)`);let worktreesDir=path169.resolve(path169.dirname(directory),SWARM_WORKTREE_DIR_NAME);try{if(fs91.existsSync(worktreesDir))fs91.rmSync(worktreesDir,{recursive:!0,force:!0}),results.push("✅ Removed .swarm-worktrees/ directory")}catch(err){results.push(`⚠️ Failed to remove .swarm-worktrees/: ${errorMessage2(err)}`)}try{let branchResult=await _internals132.cleanupOrphanedBranches(directory,[]);if(branchResult.removed.length>0)results.push(`✅ Removed ${branchResult.removed.length} orphan swarm-lane branch(es)`);if(branchResult.errors.length>0)results.push(`⚠️ Failed to remove ${branchResult.errors.length} branch(es): ${branchResult.errors.map((e)=>e.error).join("; ")}`);if(branchResult.skippedRecoveryBranches&&branchResult.skippedRecoveryBranches.length>0)results.push(`ℹ️ Preserved ${branchResult.skippedRecoveryBranches.length} branch(es) with unresolved merge-back recovery records (run /swarm status to inspect)`);if(branchResult.recoveryReadError)results.push("⚠️ Skipped all lane-branch deletions: .swarm/recovery/ was unreadable (fail-safe). Resolve or clear corrupt recovery records and re-run.")}catch(err){results.push(`⚠️ Failed to cleanup orphan branches: ${errorMessage2(err)}`)}return["## Session State Reset","",...results,"","Session state cleared. Plan, evidence, and knowledge preserved.","","**All circuit breakers and revision limits have been cleared.** You can continue in this session — fresh state will be initialized automatically on the next tool call."].join(`
2179
2179
  `)}var _internals132;var init_reset_session=__esm(()=>{init_constants();init_trajectory_logger();init_utils2();init_prm();init_state2();init_merge();init_reset_backup();_internals132={cleanupOrphanedBranches,backupSwarmStateBeforeReset}});import{mkdirSync as mkdirSync43,readdirSync as readdirSync25,renameSync as renameSync25,rmSync as rmSync14,statSync as statSync38}from"node:fs";import*as path170 from"node:path";function sanitizeSummaryId(id){if(!id||id.length===0)throw Error("Invalid summary ID: empty string");if(/\0/.test(id))throw Error("Invalid summary ID: contains null bytes");for(let i=0;i<id.length;i++)if(id.charCodeAt(i)<32)throw Error("Invalid summary ID: contains control characters");if(id.includes("..")||id.includes("../")||id.includes("..\\"))throw Error("Invalid summary ID: path traversal detected");if(!SUMMARY_ID_REGEX.test(id))throw Error(`Invalid summary ID: must match pattern ^S\\d+$, got "${id}"`);return id}async function storeSummary(directory,id,fullOutput,summaryText,maxStoredBytes){let sanitizedId=sanitizeSummaryId(id),preCheckEntry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},serializedSize=Buffer.byteLength(JSON.stringify(preCheckEntry),"utf8");if(serializedSize>maxStoredBytes)throw Error(`Summary entry size (${serializedSize} bytes) exceeds maximum (${maxStoredBytes} bytes)`);let relativePath2=path170.join("summaries",`${sanitizedId}.json`),summaryPath=validateSwarmPath(directory,relativePath2),summaryDir=path170.dirname(summaryPath),entry={id:sanitizedId,summaryText,fullOutput,timestamp:Date.now(),originalBytes:Buffer.byteLength(fullOutput,"utf8")},entryJson=JSON.stringify(entry);mkdirSync43(summaryDir,{recursive:!0});let tempPath=path170.join(summaryDir,`${sanitizedId}.json.tmp.${Date.now()}.${process.pid}`);try{await bunWrite(tempPath,entryJson),renameSync25(tempPath,summaryPath),invalidateCachedArtifact(summaryPath)}catch(error93){try{rmSync14(tempPath,{force:!0})}catch{}throw error93}}async function loadFullOutput(directory,id){let sanitizedId=sanitizeSummaryId(id),relativePath2=path170.join("summaries",`${sanitizedId}.json`);validateSwarmPath(directory,relativePath2);let content=await readSwarmFileAsync(directory,relativePath2);if(content===null)return null;try{let parsed=JSON.parse(content);if(typeof parsed.fullOutput==="string")return parsed.fullOutput;return warn(`Summary entry ${sanitizedId} missing valid fullOutput field`),null}catch(error93){return warn(`Summary entry validation failed for ${sanitizedId}: ${error93 instanceof Error?error93.message:String(error93)}`),null}}var SUMMARY_ID_REGEX;var init_manager4=__esm(()=>{init_utils2();init_utils();init_bun_compat();init_swarm_artifact_cache();SUMMARY_ID_REGEX=/^S\d+$/});async function handleRetrieveCommand(directory,args2){let summaryId=args2[0];if(!summaryId)return["## Swarm Retrieve","","Usage: `/swarm retrieve <id>`","","Example: `/swarm retrieve S1`","","Retrieves the full output that was replaced by a summary."].join(`
2180
2180
  `);try{let fullOutput=await loadFullOutput(directory,summaryId);if(fullOutput===null)return`## Summary Not Found
2181
2181
 
@@ -2189,12 +2189,12 @@ ${error93 instanceof Error?error93.message:String(error93)}`}}var init_retrieve=
2189
2189
  `),requestBytes=Buffer.byteLength(VALIDATOR_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8");return{prompt,requestBytes,promptByteLimit:Math.min(requestBytes,MAX_EPHEMERAL_PROMPT_BYTE_LIMIT),fits:requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}}function modelIdentifier2(model){return model?`${model.providerID}/${model.modelID}`:void 0}function rejectedDispatchAttempt(input,model,prompt,startedAt,error93){return{status:"error",agentName:input.agentName,modelId:modelIdentifier2(model),text:"",error:error93 instanceof Error?error93.message:String(error93),durationMs:Date.now()-startedAt,promptBytes:Buffer.byteLength(VALIDATOR_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8"),responseBytes:0}}function isTransientDispatchFailure(dispatch){if(dispatch.status==="timeout")return!0;if(dispatch.status!=="error")return!1;return isTransientProviderError(dispatch.error??"")}async function runFindingValidation(input){let candidates=canonicalizeValidationCandidates(input.findings);if(candidates.length===0)return{complete:!0,candidates,validations:[],attempts:[]};let promptRequest=buildValidatorPromptRequest(candidates,input.scopeContext);if(!promptRequest.fits)return{complete:!1,candidates,validations:[],attempts:[],error:`finding validation requires ${promptRequest.requestBytes} prompt bytes, exceeding the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling; exact diff evidence was not truncated`};let{prompt}=promptRequest,models=[input.model,...(input.fallbackModels??[]).slice(0,MAX_VALIDATOR_FALLBACK_MODELS)],attempts=[],dispatch;for(let index=0;index<models.length;index+=1){let model=models[index],startedAt=Date.now();try{dispatch=await input.dispatcher.dispatch({directory:input.directory,parentSessionId:input.parentSessionId,agentName:input.agentName,model,system:VALIDATOR_SYSTEM_PROMPT,prompt,title:`finding validation (${candidates.length})`,timeoutMs:input.timeoutMs,promptByteLimit:promptRequest.promptByteLimit,abortSignal:input.abortSignal})}catch(error93){dispatch=rejectedDispatchAttempt(input,model,prompt,startedAt,error93)}if(attempts.push(dispatch),dispatch.status==="completed")break;if(!isTransientDispatchFailure(dispatch)||index===models.length-1)break}if(!dispatch)return{complete:!1,candidates,validations:[],attempts,error:"finding validation made no model dispatch attempt"};if(dispatch.status!=="completed")return{complete:!1,candidates,validations:[],attempts,error:dispatch.error??`finding validation dispatch ended with status ${dispatch.status}`,dispatch};let extracted=extractFindingValidationsFromAgentOutput(dispatch.text),validations=extracted.validations;if(extracted.error)return{complete:!1,candidates,validations,attempts,error:`finding validation output was malformed: ${extracted.error}`,dispatch};let expectedIds=new Set(candidates.map((candidate)=>candidate.finding_id)),seenIds=new Set;for(let validation of validations){if(!expectedIds.has(validation.finding_id))return{complete:!1,candidates,validations,attempts,error:`finding validation returned unknown ID ${validation.finding_id}`,dispatch};if(seenIds.has(validation.finding_id))return{complete:!1,candidates,validations,attempts,error:`finding validation duplicated ID ${validation.finding_id}`,dispatch};seenIds.add(validation.finding_id)}let missingIds=[...expectedIds].filter((id)=>!seenIds.has(id));if(missingIds.length>0)return{complete:!1,candidates,validations,attempts,error:`finding validation omitted ${missingIds.length} required ID(s)`,dispatch};return{complete:!0,candidates,validations,attempts,dispatch}}function createFindingValidationScheduler(){let validationByIdentity=new Map;return{get pendingCount(){return validationByIdentity.size},reset:()=>validationByIdentity.clear(),schedule:(validationIdentity,run,onComplete,onError)=>{if(!validationIdentity||validationIdentity.length>2048||Array.from(validationIdentity).some((char)=>{let code=char.charCodeAt(0);return code<=31&&code!==0})||validationByIdentity.has(validationIdentity))return!1;if(validationByIdentity.size>=MAX_TRACKED_VALIDATION_SESSIONS)return!1;let reportError=(error93)=>{try{return Promise.resolve(onError?.(error93)).then(()=>{return},()=>{return})}catch{return Promise.resolve()}},runPromise;try{runPromise=run()}catch(error93){runPromise=Promise.reject(error93)}let pending=runPromise.then((result)=>{try{let completion=onComplete(result);return completion&&typeof completion.then==="function"?completion.then(()=>result,(error93)=>reportError(error93).then(()=>result)):result}catch(error93){return reportError(error93).then(()=>result)}},(error93)=>reportError(error93).then(()=>({complete:!1,candidates:[],validations:[],attempts:[],error:error93 instanceof Error?error93.message:`finding validation failed: ${String(error93)}`}))).finally(()=>{if(validationByIdentity.get(validationIdentity)===pending)validationByIdentity.delete(validationIdentity)});return validationByIdentity.set(validationIdentity,pending),!0}}}var MAX_VALIDATOR_FALLBACK_MODELS,VALIDATOR_SYSTEM_PROMPT,MAX_TRACKED_VALIDATION_SESSIONS=256;var init_finding_validator=__esm(()=>{init_agent_output_schema();init_schema();init_ephemeral_agent_dispatcher();init_provider_error_classification();MAX_VALIDATOR_FALLBACK_MODELS=FALLBACK_MODELS_MAX;VALIDATOR_SYSTEM_PROMPT=["You are an independent code-review finding validator.","You never approve code and never invent new findings.","Verify only the supplied candidate IDs against repository and diff evidence.","Default to DISPROVED; use CONFIRMED only with direct evidence and UNVERIFIED only when diligent verification cannot decide.","Return exactly one fenced ```json ... ``` wrapper and no prose outside it. Do not emit any other JSON.",'The strict root object has exactly one key, "validations"; each item has exactly "finding_id", "disposition", "confidence", and "evidence".','Schema: {"validations":[{"finding_id":"...","disposition":"CONFIRMED|DISPROVED|UNVERIFIED","confidence":0.0,"evidence":"..."}]}.'].join(`
2190
2190
  `)});function rolePrefix(agentName,role){if(agentName===role)return"";for(let separator of["_","-"," "]){let suffix=`${separator}${role}`;if(agentName.endsWith(suffix)&&agentName.length>suffix.length)return agentName.slice(0,-role.length)}return}function roleCandidates(generatedAgentNames,role){return generatedAgentNames.filter((name)=>stripKnownSwarmPrefix(name)===role)}function resolveAgentForActiveSwarm(generatedAgentNames,role,activeAgentName){let names=[...generatedAgentNames],candidates=roleCandidates(names,role);if(candidates.length===0)return role;if(activeAgentName){let activeRole=stripKnownSwarmPrefix(activeAgentName);if(activeAgentName!==activeRole&&!names.includes(activeAgentName))throw Error(`Cannot resolve ${role}: active agent "${activeAgentName}" is not present in this plugin's generated-agent registry.`);let prefix=rolePrefix(activeAgentName,activeRole);if(prefix===void 0)throw Error(`Cannot resolve ${role}: active agent "${activeAgentName}" has no generated swarm prefix.`);let preferred=`${prefix}${role}`;if(candidates.includes(preferred))return preferred;throw Error(`Cannot resolve ${role}: active agent "${activeAgentName}" belongs to a swarm without registered "${preferred}".`)}if(candidates.length===1)return candidates[0];if(candidates.includes(role))return role;throw Error(`Cannot resolve ${role}: multiple named swarms are registered and no active agent identity was supplied.`)}function resolveReviewAgentNames(generatedAgentNames,activeAgentName){let names=[...generatedAgentNames],reviewer=resolveAgentForActiveSwarm(names,"reviewer",activeAgentName),preferredValidator=`${rolePrefix(reviewer,"reviewer")??""}critic_finding_validator`,validator=names.find((name)=>name===preferredValidator)??preferredValidator;return{reviewer,validator}}function effectiveAgentConfig(config3,agentName){let role=stripKnownSwarmPrefix(agentName),defaultConfig=DEFAULT_AGENT_CONFIGS[role];if(!config3)return defaultConfig;let prefix=rolePrefix(agentName,role);if(!(config3.swarms!==void 0&&Object.keys(config3.swarms).length>0))return config3.agents?.[role]??defaultConfig;let swarmID=prefix===""?"default":prefix?prefix.slice(0,-1):void 0;return(swarmID?config3.swarms?.[swarmID]?.agents?.[role]:void 0)??config3.agents?.[role]??defaultConfig}function captureReviewAgentModelRegistry(config3,generatedAgentNames){let snapshot=Object.create(null);for(let agentName of generatedAgentNames){let agentConfig=effectiveAgentConfig(config3,agentName);snapshot[agentName]=Object.freeze({primaryModel:agentConfig?.model,fallbackModels:Object.freeze([...agentConfig?.fallback_models??[]])})}return Object.freeze(snapshot)}function reviewFallbackModelStrings(agentName,registry3){return registry3?.[agentName]?.fallbackModels??[]}function reviewPrimaryModel(agentName,registry3){return registry3?.[agentName]?.primaryModel}function resolveReviewFallbackModels(agentName,registry3){let result=[];for(let configured of reviewFallbackModelStrings(agentName,registry3))try{let parsed=parseModelString(configured);if(parsed)result.push(parsed)}catch{}return result}function optionalModelOverride(model){return model?parseModelString(model):void 0}var init_runtime2=__esm(()=>{init_constants();init_schema()});import*as child_process8 from"node:child_process";import{createHash as createHash43}from"node:crypto";import*as fs93 from"node:fs";import*as path172 from"node:path";async function resolveReviewerScopeTaskId(directory,args2){if(!args2||typeof args2!=="object")return null;let record3=args2;try{let plan=await loadPlanJsonOnly(directory);if(!plan)return null;let knownPlanTaskIds=new Set;for(let phase of plan.phases)for(let task of phase.tasks)knownPlanTaskIds.add(task.id);if(knownPlanTaskIds.size===0)return null;return resolveDelegatedPlanTaskId(record3,knownPlanTaskIds)}catch{return null}}function hasControlCharacter2(value){for(let index=0;index<value.length;index+=1){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function isContained2(root,candidate){let relative38=path172.relative(root,candidate);return relative38.length>0&&relative38!==".."&&!relative38.startsWith(`..${path172.sep}`)&&!path172.isAbsolute(relative38)}function canonicalPath(relativePath2){return relativePath2.split(path172.sep).join("/")}function pathKey(relativePath2){return process.platform==="win32"?relativePath2.toLowerCase():relativePath2}function samePath3(left,right){let a=path172.resolve(left),b=path172.resolve(right);return process.platform==="win32"?a.toLowerCase()===b.toLowerCase():a===b}function sameFileIdentity2(left,right){return(left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n)&&left.dev===right.dev&&left.ino===right.ino}function sameFileSnapshot3(left,right){return sameFileIdentity2(left,right)&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}async function missingPathParentIsContained(root,absolutePath2){let current=path172.dirname(absolutePath2);for(;;){try{let canonical=await _internals135.realpath(current);return samePath3(root,canonical)||isContained2(root,canonical)}catch(error93){if(error93.code!=="ENOENT")return!1}let parent=path172.dirname(current);if(samePath3(parent,current))return!1;current=parent}}async function readBoundedHandle(handle,maxBytes){let buffer=Buffer.alloc(maxBytes+1),offset=0;while(offset<buffer.byteLength){let{bytesRead}=await handle.read(buffer,offset,buffer.byteLength-offset,offset);if(bytesRead===0)break;offset+=bytesRead}return buffer.subarray(0,offset)}async function resolveHeadSha(directory){let child,timeoutHandle;try{return child=_internals135.spawn("git",["rev-parse","--verify","HEAD"],{cwd:directory,stdio:["ignore","pipe","ignore"],timeout:HEAD_TIMEOUT_MS,windowsHide:!0}),await new Promise((resolve71)=>{let settled=!1,stdoutBytes=0,stdoutChunks=[],finish=(value)=>{if(settled)return;if(settled=!0,timeoutHandle!==void 0)clearTimeout(timeoutHandle);resolve71(value)},killAndFail=()=>{try{child?.kill()}catch{}finish(null)};timeoutHandle=setTimeout(killAndFail,HEAD_TIMEOUT_MS),timeoutHandle.unref?.(),child?.once("error",killAndFail),child?.stdout?.on("data",(chunk)=>{let bytes=Buffer.isBuffer(chunk)?chunk:Buffer.from(chunk);if(stdoutBytes+=bytes.byteLength,stdoutBytes>HEAD_OUTPUT_BYTES){killAndFail();return}stdoutChunks.push(bytes)}),child?.once("close",(exitCode)=>{if(exitCode!==0||stdoutBytes>HEAD_OUTPUT_BYTES){finish(null);return}let sha=Buffer.concat(stdoutChunks).toString("utf-8").trim();finish(HEAD_SHA_PATTERN.test(sha)?sha:null)})})}catch{return null}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);try{child?.kill()}catch{}}}async function buildReviewerTaskScope(directory,modifiedFiles,maxBytes=DEFAULT_MAX_SCOPE_BYTES,provenance){if(modifiedFiles.length===0||modifiedFiles.length>MAX_SCOPE_FILES||!Number.isSafeInteger(maxBytes)||maxBytes<=0||maxBytes>MAX_SCOPE_BYTES2)return null;let lexicalRoot,realRoot;try{lexicalRoot=path172.resolve(directory),realRoot=await _internals135.realpath(lexicalRoot)}catch{return null}let headSha=await resolveHeadSha(realRoot);if(!headSha)return null;let candidates=new Map;for(let rawPath of modifiedFiles){if(typeof rawPath!=="string"||rawPath.length===0||hasControlCharacter2(rawPath))return null;let absolutePath2=path172.resolve(lexicalRoot,rawPath);if(!isContained2(lexicalRoot,absolutePath2))return null;let relativePath2=canonicalPath(path172.relative(lexicalRoot,absolutePath2));if(relativePath2.length===0||relativePath2.startsWith("-"))return null;candidates.set(pathKey(relativePath2),{absolutePath:absolutePath2,relativePath:relativePath2})}let ordered=[...candidates.values()].sort((left,right)=>left.relativePath.localeCompare(right.relativePath,"en"));if(ordered.length===0)return null;let totalBytes=0,stableFiles=[],deletedPaths=[],records=["opencode-swarm-reviewer-task-scope-v1",JSON.stringify({head:headSha})];if(provenance)records.push(JSON.stringify({task_id:provenance.taskId,coder_call_id:provenance.coderCallID,generation:provenance.generation,session_incarnation:provenance.sessionIncarnation}));for(let candidate of ordered){let before;try{before=await _internals135.lstatBigInt(candidate.absolutePath)}catch(error93){if(error93.code==="ENOENT"){if(!await missingPathParentIsContained(realRoot,candidate.absolutePath))return null;deletedPaths.push(candidate.absolutePath),records.push(JSON.stringify({path:candidate.relativePath,state:"deleted"}));continue}return null}if(!before.isFile()||before.isSymbolicLink())return null;let realCandidate;try{realCandidate=await _internals135.realpath(candidate.absolutePath)}catch{return null}if(!isContained2(realRoot,realCandidate))return null;if(before.size>BigInt(maxBytes-totalBytes))return null;let handle,bytes,openedBefore;try{handle=await _internals135.open(realCandidate,"r"),openedBefore=await _internals135.fileHandleStatBigInt(handle);let canonicalAfterOpen=await _internals135.realpath(candidate.absolutePath);if(!openedBefore.isFile()||!sameFileSnapshot3(before,openedBefore)||!samePath3(realCandidate,canonicalAfterOpen)||!isContained2(realRoot,canonicalAfterOpen))return null;bytes=await readBoundedHandle(handle,maxBytes-totalBytes);let openedAfter=await _internals135.fileHandleStatBigInt(handle),canonicalAfterRead=await _internals135.realpath(candidate.absolutePath);if(!sameFileSnapshot3(openedBefore,openedAfter)||!samePath3(realCandidate,canonicalAfterRead)||!isContained2(realRoot,canonicalAfterRead)||BigInt(bytes.byteLength)!==openedBefore.size)return null}catch{return null}finally{await handle?.close().catch(()=>{})}totalBytes+=bytes.byteLength,stableFiles.push({absolutePath:candidate.absolutePath,canonicalPath:realCandidate,stat:openedBefore}),records.push(JSON.stringify({path:candidate.relativePath,state:"file",bytes:bytes.byteLength,sha256:createHash43("sha256").update(bytes).digest("hex")}))}for(let stable of stableFiles)try{let current=await _internals135.lstatBigInt(stable.absolutePath),canonical=await _internals135.realpath(stable.absolutePath);if(!current.isFile()||current.isSymbolicLink()||!sameFileSnapshot3(stable.stat,current)||!samePath3(stable.canonicalPath,canonical)||!isContained2(realRoot,canonical))return null}catch{return null}for(let deletedPath of deletedPaths)try{return await _internals135.lstatBigInt(deletedPath),null}catch(error93){if(error93.code!=="ENOENT"||!await missingPathParentIsContained(realRoot,deletedPath))return null}if(await resolveHeadSha(realRoot)!==headSha)return null;return{content:`${records.join(`
2191
2191
  `)}
2192
- `,description:REVIEWER_TASK_SCOPE_DESCRIPTION,files:ordered.map((candidate)=>candidate.relativePath),headSha,...provenance?{taskId:provenance.taskId,coderCallID:provenance.coderCallID,generation:provenance.generation,sessionIncarnation:provenance.sessionIncarnation}:{}}}async function resolveReviewerTaskScope(directory,sessionID,maxBytes=DEFAULT_MAX_SCOPE_BYTES,options={}){let session=swarmState.agentSessions.get(sessionID);if(!session)return null;if(options.consumeHandoff){let{expectedTaskId,reviewerCallID}=options;if(!expectedTaskId||!reviewerCallID)return null;let handoff=peekReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId:expectedTaskId,reviewerCallID,now:options.now});if(!handoff)return null;let snapshot=handoff.reviewerDispatchScope;if(!snapshot)return null;let current=await buildReviewerTaskScope(directory,handoff.modifiedFiles,maxBytes,{taskId:handoff.taskId,coderCallID:handoff.coderCallID,generation:handoff.generation,sessionIncarnation:handoff.sessionIncarnation});if(!current||computeScopeFingerprint(current.content,current.description).hash!==snapshot.hash||current.description!==snapshot.description||current.headSha!==snapshot.headSha||JSON.stringify(current.files)!==JSON.stringify(snapshot.files))return null;return current}return buildReviewerTaskScope(directory,session.modifiedFilesThisCoderTask,maxBytes)}var MAX_SCOPE_FILES=256,DEFAULT_MAX_SCOPE_BYTES=262144,MAX_SCOPE_BYTES2=2097152,HEAD_TIMEOUT_MS=5000,HEAD_OUTPUT_BYTES=256,HEAD_SHA_PATTERN,REVIEWER_TASK_SCOPE_DESCRIPTION="reviewer-task-files-v1",_internals135;var init_review_receipt_scope=__esm(()=>{init_manager();init_state2();init_delegation_gate();init_review_receipt();HEAD_SHA_PATTERN=/^[0-9a-f]{40,64}$/i;_internals135={spawn:child_process8.spawn,realpath:fs93.promises.realpath,lstatBigInt:(path173)=>fs93.promises.lstat(path173,{bigint:!0}),open:fs93.promises.open,fileHandleStatBigInt:(handle)=>handle.stat({bigint:!0})}});function inferSeverity(line){let upper=line.toUpperCase();if(upper.includes("CRITICAL"))return"critical";if(upper.includes("HIGH"))return"high";if(upper.includes("LOW"))return"low";if(upper.includes("INFO"))return"info";return"medium"}function collectSectionLines(lines,section){let headerPattern=new RegExp(`^\\s*${section}\\s*:\\s*(.*)$`,"i"),nextSectionPattern=new RegExp(`^\\s*(${SECTION_FIELDS.join("|")})\\s*:`,"i"),collected=[],inSection=!1;for(let line of lines){if(!inSection){let m=line.match(headerPattern);if(m){inSection=!0;let inline=m[1]?.trim();if(inline&&!/^(none|n\/a)\.?$/i.test(inline))collected.push(inline)}continue}if(nextSectionPattern.test(line)||/^\s*```/.test(line))break;let cleaned=line.replace(/^\s*(?:[-*•]|\d+[.)])\s*/,"").trim();if(cleaned)collected.push(cleaned)}return collected}function parseReviewerOutput(text,options={}){if(!text||typeof text!=="string")return null;let structured=options.structured===!1?{findings:[],review:void 0,error:"structured parsing disabled"}:extractReviewFindingsFromAgentOutput(text),verdictTokens=[...text.matchAll(VERDICT_LINE_PATTERN)].map((m)=>m[1].toUpperCase());if(verdictTokens.length!==1)return null;let legacyVerdict=verdictTokens[0];if(structured.review){if(structured.review.verdict!==legacyVerdict)return null;let riskTokens2=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()),fixes2=collectSectionLines(text.split(/\r?\n/),"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict:structured.review.verdict==="APPROVED"?"approved":"rejected",risk:riskTokens2.at(-1),issues:structured.findings.map((finding)=>({text:`${finding.title}: ${finding.body}`.slice(0,500),severity:finding.severity,location:`${finding.file}:${finding.line_start}`,finding})),fixes:fixes2,outputMode:"structured",overallConfidence:structured.review.overall_confidence,structuredFindings:structured.findings}}let verdict=legacyVerdict==="APPROVED"?"approved":"rejected",risk=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()).at(-1),lines=text.split(/\r?\n/),issues=collectSectionLines(lines,"ISSUES").slice(0,50).map((line)=>{let location=line.match(LOCATION_PATTERN)?.[0];return{text:line.slice(0,500),severity:inferSeverity(line),location}}),fixes=collectSectionLines(lines,"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict,risk,issues,fixes,outputMode:"legacy"}}function findingId(finding){return finding?canonicalizeValidationCandidates([finding])[0]?.finding_id:void 0}function effectiveSeverityForFinding(finding,minConfidence){return finding.confidence<minConfidence?"info":finding.severity}function isValidationCandidate(finding,minConfidence){let effectiveSeverity=effectiveSeverityForFinding(finding,minConfidence);return effectiveSeverity==="high"||effectiveSeverity==="critical"}function validatorForReviewer(reviewer){return`${stripKnownSwarmPrefix(reviewer)===reviewer?"":reviewer.slice(0,reviewer.length-8)}critic_finding_validator`}function validationErrorText(error93){return(error93 instanceof Error?error93.message:String(error93)).trim()||"unknown validation error"}function emitStageBValidationTelemetry(sessionID,validatorAgent,result,costFields){try{_internals136.delegationEnd(sessionID,validatorAgent,STAGE_B_VALIDATION_TASK_ID,result,costFields)}catch(error93){warn(`[review-receipt-collector] validation telemetry failed: ${validationErrorText(error93)}`)}}function materializeValidationOutcome(candidates,result){if(result.complete)return result.validations;let candidateIds=new Set(candidates.map((candidate)=>candidate.finding_id)),byId=new Map(result.validations.filter((validation)=>candidateIds.has(validation.finding_id)).map((validation)=>[validation.finding_id,validation])),reason=(result.error??"validator did not return a complete exact-ID result").slice(0,1900);return candidates.map((candidate)=>byId.get(candidate.finding_id)??{finding_id:candidate.finding_id,disposition:"UNVERIFIED",confidence:0,evidence:`Validation incomplete: ${reason}`})}function isTaskTool2(tool3){return tool3==="Task"||tool3==="task"}function hasExactScopeIdentity(scope){return typeof scope.taskId==="string"&&typeof scope.coderCallID==="string"&&typeof scope.generation==="number"&&typeof scope.sessionIncarnation==="string"}async function reviewerScopeRemainsCurrent(input){if(!hasExactScopeIdentity(input.scope))return!0;if(input.reviewerCallID){let claim=peekReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID});if(!claim||claim.coderCallID!==input.scope.coderCallID||claim.generation!==input.scope.generation||claim.sessionIncarnation!==input.scope.sessionIncarnation)return!1}let currentScope=await _internals136.buildReviewerTaskScope(input.directory,input.scope.files,input.maxBytes,{taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation});return currentScope!==null&&isReviewerScopeGenerationCurrent({parentSessionID:input.sessionID,taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation})&&currentScope.headSha===input.scope.headSha&&currentScope.content===input.scope.content&&currentScope.description===input.scope.description&&JSON.stringify(currentScope.files)===JSON.stringify(input.scope.files)}function discardConsumedReviewerClaim(input){if(!input.reviewerCallID||!hasExactScopeIdentity(input.scope))return;discardReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID})}async function collectReviewerReceiptFromTranscript(directory,input,validationOptions={}){try{let validationConfig=validationOptions.config;if(validationConfig?.enabled!==!0)return null;if(input.targetAgent&&stripKnownSwarmPrefix(input.targetAgent).toLowerCase()!=="reviewer")return null;let sessionID=input.sessionID??input.sessionId;if(!sessionID)return null;let scope=await _internals136.resolveReviewerTaskScope(directory,sessionID,validationConfig.max_diff_kb*1024,input.consumeHandoff?{consumeHandoff:!0,expectedTaskId:input.taskId,reviewerCallID:input.reviewerCallID}:void 0);if(!scope)return null;if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;if(!input.transcript)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let parsed=parseReviewerOutput(input.transcript,{structured:validationConfig.structured_findings!==!1});if(!parsed)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let minConfidence=validationConfig.min_confidence,receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,checkedAspects:["code-review"],validatedClaims:[`VERDICT: APPROVED${parsed.risk?` (risk ${parsed.risk})`:""}`],caveats:parsed.issues.map((i)=>i.text),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence}):buildRejectedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,blockingFindings:parsed.issues.map((i)=>({location:i.location??"unknown",summary:i.text,severity:i.severity,finding_id:findingId(i.finding),line:i.finding?.line_start,title:i.finding?.title,body:i.finding?.body,confidence:i.finding?.confidence,file:i.finding?.file,line_start:i.finding?.line_start,line_end:i.finding?.line_end,effective_severity:i.finding?effectiveSeverityForFinding(i.finding,minConfidence):void 0})),evidenceReferences:parsed.issues.map((i)=>i.location).filter((loc)=>Boolean(loc)),passConditions:parsed.fixes,summary:`Reviewer REJECTED${parsed.risk?` (risk ${parsed.risk})`:""}`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence});if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let scopeBecameStale=!1,receiptPath;try{receiptPath=await _internals136.persistReviewReceipt(directory,receipt,{verifyCurrent:async()=>{let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID});if(!current)scopeBecameStale=!0;return current}})}catch(error93){if(scopeBecameStale)discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});throw error93}discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});let candidates=parsed.structuredFindings?.filter((finding)=>isValidationCandidate(finding,minConfidence))??[];if(sessionID&&validationOptions.dispatcher&&validationConfig?.enabled&&validationConfig.validate_findings&&candidates.length>0){let reviewer=input.targetAgent??"reviewer",canonicalCandidates=canonicalizeValidationCandidates(candidates),validatorAgent=validatorForReviewer(reviewer),immutableScope={...scope,files:[...scope.files]},receiptIdentity={id:receipt.id,scopeHash:receipt.scope_fingerprint.hash,scopeDescription:receipt.scope_fingerprint.scope_description},persistAndAdvise=async(result)=>{for(let attempt of result.attempts)emitStageBValidationTelemetry(sessionID,validatorAgent,attempt.status,{...attempt.costFields,gate:"finding_validation"});let validationScopeIsCurrent=async()=>{if(!hasExactScopeIdentity(immutableScope))return!0;let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope:immutableScope,maxBytes:validationConfig.max_diff_kb*1024}),currentFingerprint=current?computeScopeFingerprint(immutableScope.content,immutableScope.description):null;return current&&currentFingerprint?.hash===receiptIdentity.scopeHash&&currentFingerprint.scope_description===receiptIdentity.scopeDescription},discardStaleValidation=()=>{warn("[review-receipt-collector] Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.");try{validationOptions.injectAdvisory?.(sessionID,"Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.")}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}};if(!await validationScopeIsCurrent()){discardStaleValidation();return}let validations=materializeValidationOutcome(canonicalCandidates,result),validationScopeBecameStale=!1;try{await _internals136.updateReviewReceiptValidations(receiptPath,validations,{expectedIdentity:receiptIdentity,verifyCurrent:async()=>{let current=await validationScopeIsCurrent();if(!current)validationScopeBecameStale=!0;return current}})}catch(error93){if(validationScopeBecameStale){discardStaleValidation();return}warn(`[review-receipt-collector] validation persistence failed: ${validationErrorText(error93)}`);try{validationOptions.injectAdvisory?.(sessionID,`Independent finding validation completed but was not persisted: ${validationErrorText(error93)}. Receipt: ${receiptPath}`)}catch(advisoryError){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(advisoryError)}`)}return}let counts={confirmed:validations.filter((item)=>item.disposition==="CONFIRMED").length,disproved:validations.filter((item)=>item.disposition==="DISPROVED").length,unverified:validations.filter((item)=>item.disposition==="UNVERIFIED").length};try{validationOptions.injectAdvisory?.(sessionID,result.complete?`Independent finding validation completed: ${counts.confirmed} confirmed, ${counts.disproved} disproved, ${counts.unverified} unverified. Receipt: ${receiptPath}`:`Independent finding validation was incomplete: ${result.error??"unknown error"}. ${counts.unverified} finding(s) recorded as UNVERIFIED. Receipt: ${receiptPath}`)}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}},validationIdentity=[sessionID,receipt.id,immutableScope.taskId??"legacy-task",immutableScope.coderCallID??"legacy-coder-call",String(immutableScope.generation??"legacy-generation"),immutableScope.sessionIncarnation??"legacy-incarnation"].join("\x00"),validationScheduler=validationOptions.validationScheduler;if(!validationScheduler)return await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because the owning plugin instance did not provide its bounded validation scheduler"}),receiptPath;if(!validationScheduler.schedule(validationIdentity,()=>runFindingValidation({dispatcher:validationOptions.dispatcher,directory,parentSessionId:sessionID,agentName:validatorAgent,model:optionalModelOverride(validationConfig.validation_model),fallbackModels:resolveReviewFallbackModels(validatorAgent,validationOptions.agentModelRegistry),timeoutMs:validationConfig.validation_timeout_ms,findings:canonicalCandidates,scopeContext:{selector:{kind:"working-tree"},canonicalText:immutableScope.content,scopeHash:receiptIdentity.scopeHash,headSha:immutableScope.headSha,completeness:{complete:!0,truncated:!1,skipReasons:[]},scopeDescription:immutableScope.description,files:[...immutableScope.files]}}),persistAndAdvise,(error93)=>persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:`validator execution failed: ${validationErrorText(error93)}`})))await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because this exact receipt generation is already being validated or the 256-validation capacity is full"})}return receiptPath}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}async function collectReviewerReceiptAfter(directory,input,output,validationOptions={}){try{if(validationOptions.config?.enabled!==!0)return null;if(!isTaskTool2(input.tool))return null;let taskResult=classifyTaskResult(output);if(taskResult==="running")return null;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return null;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return null;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"",transcript=typeof output.output==="string"?output.output:"",sessionID=typeof input.sessionID==="string"?input.sessionID:void 0,reviewerCallID=typeof input.callID==="string"?input.callID:void 0;if(!sessionID)return null;let taskId=reviewerCallID?await resolveReviewerScopeTaskId(directory,input.args):void 0;if(reviewerCallID&&!taskId)return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,reviewerCallID}),null;if(reviewerCallID&&taskId&&taskResult!=="success")return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId,reviewerCallID}),null;return await collectReviewerReceiptFromTranscript(directory,{targetAgent:parsedArgs.targetAgent,prompt,transcript,sessionID,taskId:taskId??void 0,reviewerCallID,consumeHandoff:reviewerCallID!==void 0},validationOptions)}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}var SECTION_FIELDS,LOCATION_PATTERN,VERDICT_LINE_PATTERN,RISK_LINE_PATTERN,STAGE_B_VALIDATION_TASK_ID="reviewer-task-validation",_internals136;var init_review_receipt_collector=__esm(()=>{init_agent_output_schema();init_schema();init_finding_validator();init_runtime2();init_state2();init_telemetry();init_logger();init_review_receipt();init_review_receipt_scope();init_skill_propagation_gate();init_task_result_classifier();SECTION_FIELDS=["VERDICT","REUSE_RE_VERIFICATION","RISK","ISSUES","ACCEPTANCE_SATISFACTION","SKILL_COMPLIANCE","DIRECTIVE_COMPLIANCE","FIXES"],LOCATION_PATTERN=/([\w./-]+\.[A-Za-z]{1,8}):(\d{1,6})/;VERDICT_LINE_PATTERN=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(APPROVED|REJECTED)\s*$/gim,RISK_LINE_PATTERN=/^\s*(?:\*\*)?RISK(?:\*\*)?\s*:\s*(LOW|MEDIUM|HIGH|CRITICAL)\b/gim;_internals136={delegationEnd:telemetry.delegationEnd,resolveReviewerTaskScope,buildReviewerTaskScope,persistReviewReceipt,updateReviewReceiptValidations}});import*as fs94 from"node:fs";import*as path173 from"node:path";function autoReviewEvidenceRelativePath(trigger,scopeHash,phase){if((trigger==="phase_completion"||trigger==="plan_completion")&&Number.isInteger(phase)&&(phase??0)>0)return path173.join("evidence",String(phase),"auto-review.json");return path173.join("evidence","auto-review",`${trigger}-${scopeHash.slice(0,64)}.json`)}async function persistAutoReviewEvidence(directory,evidence2,options={}){let target=validateSwarmPath(directory,autoReviewEvidenceRelativePath(evidence2.trigger,evidence2.scope.hash,evidence2.phase));fs94.mkdirSync(path173.dirname(target),{recursive:!0});let tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await bunWrite(tempPath,`${JSON.stringify(evidence2,null,2)}
2192
+ `,description:REVIEWER_TASK_SCOPE_DESCRIPTION,files:ordered.map((candidate)=>candidate.relativePath),headSha,...provenance?{taskId:provenance.taskId,coderCallID:provenance.coderCallID,generation:provenance.generation,sessionIncarnation:provenance.sessionIncarnation}:{}}}async function resolveReviewerTaskScope(directory,sessionID,maxBytes=DEFAULT_MAX_SCOPE_BYTES,options={}){let session=swarmState.agentSessions.get(sessionID);if(!session)return null;if(options.consumeHandoff){let{expectedTaskId,reviewerCallID}=options;if(!expectedTaskId||!reviewerCallID)return null;let handoff=peekReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId:expectedTaskId,reviewerCallID,now:options.now});if(!handoff)return null;let snapshot=handoff.reviewerDispatchScope;if(!snapshot)return null;let current=await buildReviewerTaskScope(directory,handoff.modifiedFiles,maxBytes,{taskId:handoff.taskId,coderCallID:handoff.coderCallID,generation:handoff.generation,sessionIncarnation:handoff.sessionIncarnation});if(!current||computeScopeFingerprint(current.content,current.description).hash!==snapshot.hash||current.description!==snapshot.description||current.headSha!==snapshot.headSha||JSON.stringify(current.files)!==JSON.stringify(snapshot.files))return null;return current}return buildReviewerTaskScope(directory,session.modifiedFilesThisCoderTask,maxBytes)}var MAX_SCOPE_FILES=256,DEFAULT_MAX_SCOPE_BYTES=262144,MAX_SCOPE_BYTES2=2097152,HEAD_TIMEOUT_MS=5000,HEAD_OUTPUT_BYTES=256,HEAD_SHA_PATTERN,REVIEWER_TASK_SCOPE_DESCRIPTION="reviewer-task-files-v1",_internals135;var init_review_receipt_scope=__esm(()=>{init_manager();init_state2();init_delegation_gate();init_review_receipt();HEAD_SHA_PATTERN=/^[0-9a-f]{40,64}$/i;_internals135={spawn:child_process8.spawn,realpath:fs93.promises.realpath,lstatBigInt:(path173)=>fs93.promises.lstat(path173,{bigint:!0}),open:fs93.promises.open,fileHandleStatBigInt:(handle)=>handle.stat({bigint:!0})}});function inferSeverity(line){let upper=line.toUpperCase();if(upper.includes("CRITICAL"))return"critical";if(upper.includes("HIGH"))return"high";if(upper.includes("LOW"))return"low";if(upper.includes("INFO"))return"info";return"medium"}function collectSectionLines(lines,section){let headerPattern=new RegExp(`^\\s*${section}\\s*:\\s*(.*)$`,"i"),nextSectionPattern=new RegExp(`^\\s*(${SECTION_FIELDS.join("|")})\\s*:`,"i"),collected=[],inSection=!1;for(let line of lines){if(!inSection){let m=line.match(headerPattern);if(m){inSection=!0;let inline=m[1]?.trim();if(inline&&!/^(none|n\/a)\.?$/i.test(inline))collected.push(inline)}continue}if(nextSectionPattern.test(line)||/^\s*```/.test(line))break;let cleaned=line.replace(/^\s*(?:[-*•]|\d+[.)])\s*/,"").trim();if(cleaned)collected.push(cleaned)}return collected}function parseReviewerOutput(text,options={}){if(!text||typeof text!=="string")return null;let structured=options.structured===!1?{findings:[],review:void 0,error:"structured parsing disabled"}:extractReviewFindingsFromAgentOutput(text),verdictTokens=[...text.matchAll(VERDICT_LINE_PATTERN)].map((m)=>m[1].toUpperCase());if(verdictTokens.length!==1)return null;let legacyVerdict=verdictTokens[0];if(structured.review){if(structured.review.verdict!==legacyVerdict)return null;let riskTokens2=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()),fixes2=collectSectionLines(text.split(/\r?\n/),"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict:structured.review.verdict==="APPROVED"?"approved":"rejected",risk:riskTokens2.at(-1),issues:structured.findings.map((finding)=>({text:`${finding.title}: ${finding.body}`.slice(0,500),severity:finding.severity,location:`${finding.file}:${finding.line_start}`,finding})),fixes:fixes2,outputMode:"structured",overallConfidence:structured.review.overall_confidence,structuredFindings:structured.findings}}let verdict=legacyVerdict==="APPROVED"?"approved":"rejected",risk=[...text.matchAll(RISK_LINE_PATTERN)].map((m)=>m[1].toUpperCase()).at(-1),lines=text.split(/\r?\n/),issues=collectSectionLines(lines,"ISSUES").slice(0,50).map((line)=>{let location=line.match(LOCATION_PATTERN)?.[0];return{text:line.slice(0,500),severity:inferSeverity(line),location}}),fixes=collectSectionLines(lines,"FIXES").slice(0,50).map((line)=>line.slice(0,500));return{verdict,risk,issues,fixes,outputMode:"legacy"}}function findingId(finding){return finding?canonicalizeValidationCandidates([finding])[0]?.finding_id:void 0}function effectiveSeverityForFinding(finding,minConfidence){return finding.confidence<minConfidence?"info":finding.severity}function isValidationCandidate(finding,minConfidence){let effectiveSeverity=effectiveSeverityForFinding(finding,minConfidence);return effectiveSeverity==="high"||effectiveSeverity==="critical"}function validatorForReviewer(reviewer){return`${stripKnownSwarmPrefix(reviewer)===reviewer?"":reviewer.slice(0,reviewer.length-8)}critic_finding_validator`}function validationErrorText(error93){return(error93 instanceof Error?error93.message:String(error93)).trim()||"unknown validation error"}function emitStageBValidationTelemetry(sessionID,validatorAgent,result,costFields){try{_internals136.delegationBegin(sessionID,validatorAgent,STAGE_B_VALIDATION_TASK_ID),_internals136.delegationEnd(sessionID,validatorAgent,STAGE_B_VALIDATION_TASK_ID,result,costFields)}catch(error93){warn(`[review-receipt-collector] validation telemetry failed: ${validationErrorText(error93)}`)}}function materializeValidationOutcome(candidates,result){if(result.complete)return result.validations;let candidateIds=new Set(candidates.map((candidate)=>candidate.finding_id)),byId=new Map(result.validations.filter((validation)=>candidateIds.has(validation.finding_id)).map((validation)=>[validation.finding_id,validation])),reason=(result.error??"validator did not return a complete exact-ID result").slice(0,1900);return candidates.map((candidate)=>byId.get(candidate.finding_id)??{finding_id:candidate.finding_id,disposition:"UNVERIFIED",confidence:0,evidence:`Validation incomplete: ${reason}`})}function isTaskTool2(tool3){return tool3==="Task"||tool3==="task"}function hasExactScopeIdentity(scope){return typeof scope.taskId==="string"&&typeof scope.coderCallID==="string"&&typeof scope.generation==="number"&&typeof scope.sessionIncarnation==="string"}async function reviewerScopeRemainsCurrent(input){if(!hasExactScopeIdentity(input.scope))return!0;if(input.reviewerCallID){let claim=peekReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID});if(!claim||claim.coderCallID!==input.scope.coderCallID||claim.generation!==input.scope.generation||claim.sessionIncarnation!==input.scope.sessionIncarnation)return!1}let currentScope=await _internals136.buildReviewerTaskScope(input.directory,input.scope.files,input.maxBytes,{taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation});return currentScope!==null&&isReviewerScopeGenerationCurrent({parentSessionID:input.sessionID,taskId:input.scope.taskId,coderCallID:input.scope.coderCallID,generation:input.scope.generation,sessionIncarnation:input.scope.sessionIncarnation})&&currentScope.headSha===input.scope.headSha&&currentScope.content===input.scope.content&&currentScope.description===input.scope.description&&JSON.stringify(currentScope.files)===JSON.stringify(input.scope.files)}function discardConsumedReviewerClaim(input){if(!input.reviewerCallID||!hasExactScopeIdentity(input.scope))return;discardReviewerScopeGenerationClaim({parentSessionID:input.sessionID,taskId:input.scope.taskId,reviewerCallID:input.reviewerCallID})}async function collectReviewerReceiptFromTranscript(directory,input,validationOptions={}){try{let validationConfig=validationOptions.config;if(validationConfig?.enabled!==!0)return null;if(input.targetAgent&&stripKnownSwarmPrefix(input.targetAgent).toLowerCase()!=="reviewer")return null;let sessionID=input.sessionID??input.sessionId;if(!sessionID)return null;let scope=await _internals136.resolveReviewerTaskScope(directory,sessionID,validationConfig.max_diff_kb*1024,input.consumeHandoff?{consumeHandoff:!0,expectedTaskId:input.taskId,reviewerCallID:input.reviewerCallID}:void 0);if(!scope)return null;if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;if(!input.transcript)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let parsed=parseReviewerOutput(input.transcript,{structured:validationConfig.structured_findings!==!1});if(!parsed)return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let minConfidence=validationConfig.min_confidence,receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,checkedAspects:["code-review"],validatedClaims:[`VERDICT: APPROVED${parsed.risk?` (risk ${parsed.risk})`:""}`],caveats:parsed.issues.map((i)=>i.text),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence}):buildRejectedReceipt({agent:"reviewer",sessionId:sessionID,scopeContent:scope.content,scopeDescription:scope.description,blockingFindings:parsed.issues.map((i)=>({location:i.location??"unknown",summary:i.text,severity:i.severity,finding_id:findingId(i.finding),line:i.finding?.line_start,title:i.finding?.title,body:i.finding?.body,confidence:i.finding?.confidence,file:i.finding?.file,line_start:i.finding?.line_start,line_end:i.finding?.line_end,effective_severity:i.finding?effectiveSeverityForFinding(i.finding,minConfidence):void 0})),evidenceReferences:parsed.issues.map((i)=>i.location).filter((loc)=>Boolean(loc)),passConditions:parsed.fixes,summary:`Reviewer REJECTED${parsed.risk?` (risk ${parsed.risk})`:""}`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence});if(!await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID}))return discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope}),null;let scopeBecameStale=!1,receiptPath;try{receiptPath=await _internals136.persistReviewReceipt(directory,receipt,{verifyCurrent:async()=>{let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope,maxBytes:validationConfig.max_diff_kb*1024,reviewerCallID:input.reviewerCallID});if(!current)scopeBecameStale=!0;return current}})}catch(error93){if(scopeBecameStale)discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});throw error93}discardConsumedReviewerClaim({sessionID,reviewerCallID:input.reviewerCallID,scope});let candidates=parsed.structuredFindings?.filter((finding)=>isValidationCandidate(finding,minConfidence))??[];if(sessionID&&validationOptions.dispatcher&&validationConfig?.enabled&&validationConfig.validate_findings&&candidates.length>0){let reviewer=input.targetAgent??"reviewer",canonicalCandidates=canonicalizeValidationCandidates(candidates),validatorAgent=validatorForReviewer(reviewer),immutableScope={...scope,files:[...scope.files]},receiptIdentity={id:receipt.id,scopeHash:receipt.scope_fingerprint.hash,scopeDescription:receipt.scope_fingerprint.scope_description},persistAndAdvise=async(result)=>{for(let attempt of result.attempts)emitStageBValidationTelemetry(sessionID,validatorAgent,attempt.status,{...attempt.costFields,gate:"finding_validation"});let validationScopeIsCurrent=async()=>{if(!hasExactScopeIdentity(immutableScope))return!0;let current=await reviewerScopeRemainsCurrent({directory,sessionID,scope:immutableScope,maxBytes:validationConfig.max_diff_kb*1024}),currentFingerprint=current?computeScopeFingerprint(immutableScope.content,immutableScope.description):null;return current&&currentFingerprint?.hash===receiptIdentity.scopeHash&&currentFingerprint.scope_description===receiptIdentity.scopeDescription},discardStaleValidation=()=>{warn("[review-receipt-collector] Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.");try{validationOptions.injectAdvisory?.(sessionID,"Independent finding validation was discarded as stale because the exact reviewed scope changed before validation completed.")}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}};if(!await validationScopeIsCurrent()){discardStaleValidation();return}let validations=materializeValidationOutcome(canonicalCandidates,result),validationScopeBecameStale=!1;try{await _internals136.updateReviewReceiptValidations(receiptPath,validations,{expectedIdentity:receiptIdentity,verifyCurrent:async()=>{let current=await validationScopeIsCurrent();if(!current)validationScopeBecameStale=!0;return current}})}catch(error93){if(validationScopeBecameStale){discardStaleValidation();return}warn(`[review-receipt-collector] validation persistence failed: ${validationErrorText(error93)}`);try{validationOptions.injectAdvisory?.(sessionID,`Independent finding validation completed but was not persisted: ${validationErrorText(error93)}. Receipt: ${receiptPath}`)}catch(advisoryError){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(advisoryError)}`)}return}let counts={confirmed:validations.filter((item)=>item.disposition==="CONFIRMED").length,disproved:validations.filter((item)=>item.disposition==="DISPROVED").length,unverified:validations.filter((item)=>item.disposition==="UNVERIFIED").length};try{validationOptions.injectAdvisory?.(sessionID,result.complete?`Independent finding validation completed: ${counts.confirmed} confirmed, ${counts.disproved} disproved, ${counts.unverified} unverified. Receipt: ${receiptPath}`:`Independent finding validation was incomplete: ${result.error??"unknown error"}. ${counts.unverified} finding(s) recorded as UNVERIFIED. Receipt: ${receiptPath}`)}catch(error93){warn(`[review-receipt-collector] validation advisory injection failed: ${validationErrorText(error93)}`)}},validationIdentity=[sessionID,receipt.id,immutableScope.taskId??"legacy-task",immutableScope.coderCallID??"legacy-coder-call",String(immutableScope.generation??"legacy-generation"),immutableScope.sessionIncarnation??"legacy-incarnation"].join("\x00"),validationScheduler=validationOptions.validationScheduler;if(!validationScheduler)return await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because the owning plugin instance did not provide its bounded validation scheduler"}),receiptPath;if(!validationScheduler.schedule(validationIdentity,()=>runFindingValidation({dispatcher:validationOptions.dispatcher,directory,parentSessionId:sessionID,agentName:validatorAgent,model:optionalModelOverride(validationConfig.validation_model),fallbackModels:resolveReviewFallbackModels(validatorAgent,validationOptions.agentModelRegistry),timeoutMs:validationConfig.validation_timeout_ms,findings:canonicalCandidates,scopeContext:{selector:{kind:"working-tree"},canonicalText:immutableScope.content,scopeHash:receiptIdentity.scopeHash,headSha:immutableScope.headSha,completeness:{complete:!0,truncated:!1,skipReasons:[]},scopeDescription:immutableScope.description,files:[...immutableScope.files]}}),persistAndAdvise,(error93)=>persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:`validator execution failed: ${validationErrorText(error93)}`})))await persistAndAdvise({complete:!1,candidates:canonicalCandidates,validations:[],attempts:[],error:"validation scheduling refused because this exact receipt generation is already being validated or the 256-validation capacity is full"})}return receiptPath}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}async function collectReviewerReceiptAfter(directory,input,output,validationOptions={}){try{if(validationOptions.config?.enabled!==!0)return null;if(!isTaskTool2(input.tool))return null;let taskResult=classifyTaskResult(output);if(taskResult==="running")return null;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return null;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return null;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"",transcript=typeof output.output==="string"?output.output:"",sessionID=typeof input.sessionID==="string"?input.sessionID:void 0,reviewerCallID=typeof input.callID==="string"?input.callID:void 0;if(!sessionID)return null;let taskId=reviewerCallID?await resolveReviewerScopeTaskId(directory,input.args):void 0;if(reviewerCallID&&!taskId)return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,reviewerCallID}),null;if(reviewerCallID&&taskId&&taskResult!=="success")return discardReviewerScopeGenerationClaim({parentSessionID:sessionID,taskId,reviewerCallID}),null;return await collectReviewerReceiptFromTranscript(directory,{targetAgent:parsedArgs.targetAgent,prompt,transcript,sessionID,taskId:taskId??void 0,reviewerCallID,consumeHandoff:reviewerCallID!==void 0},validationOptions)}catch(err){return warn(`[review-receipt-collector] failed: ${err instanceof Error?err.message:String(err)}`),null}}var SECTION_FIELDS,LOCATION_PATTERN,VERDICT_LINE_PATTERN,RISK_LINE_PATTERN,STAGE_B_VALIDATION_TASK_ID="reviewer-task-validation",_internals136;var init_review_receipt_collector=__esm(()=>{init_agent_output_schema();init_schema();init_finding_validator();init_runtime2();init_state2();init_telemetry();init_logger();init_review_receipt();init_review_receipt_scope();init_skill_propagation_gate();init_task_result_classifier();SECTION_FIELDS=["VERDICT","REUSE_RE_VERIFICATION","RISK","ISSUES","ACCEPTANCE_SATISFACTION","SKILL_COMPLIANCE","DIRECTIVE_COMPLIANCE","FIXES"],LOCATION_PATTERN=/([\w./-]+\.[A-Za-z]{1,8}):(\d{1,6})/;VERDICT_LINE_PATTERN=/^\s*(?:\*\*)?VERDICT(?:\*\*)?\s*:\s*(APPROVED|REJECTED)\s*$/gim,RISK_LINE_PATTERN=/^\s*(?:\*\*)?RISK(?:\*\*)?\s*:\s*(LOW|MEDIUM|HIGH|CRITICAL)\b/gim;_internals136={delegationBegin:telemetry.delegationBegin,delegationEnd:telemetry.delegationEnd,resolveReviewerTaskScope,buildReviewerTaskScope,persistReviewReceipt,updateReviewReceiptValidations}});import*as fs94 from"node:fs";import*as path173 from"node:path";function autoReviewEvidenceRelativePath(trigger,scopeHash,phase){if((trigger==="phase_completion"||trigger==="plan_completion")&&Number.isInteger(phase)&&(phase??0)>0)return path173.join("evidence",String(phase),"auto-review.json");return path173.join("evidence","auto-review",`${trigger}-${scopeHash.slice(0,64)}.json`)}async function persistAutoReviewEvidence(directory,evidence2,options={}){let target=validateSwarmPath(directory,autoReviewEvidenceRelativePath(evidence2.trigger,evidence2.scope.hash,evidence2.phase));fs94.mkdirSync(path173.dirname(target),{recursive:!0});let tempPath=`${target}.tmp.${Date.now()}.${Math.floor(Math.random()*1e9)}`;try{await bunWrite(tempPath,`${JSON.stringify(evidence2,null,2)}
2193
2193
  `);let safeTemp=validateSwarmPath(directory,path173.relative(path173.join(directory,".swarm"),tempPath)),tempStat=fs94.lstatSync(safeTemp);if(!tempStat.isFile()||tempStat.isSymbolicLink())throw Error("auto-review evidence temp path must be a real file");if(options.verifyCurrent&&!await options.verifyCurrent())throw new ReviewScopeStaleError("auto-review scope became stale before evidence commit");let safeTarget=validateSwarmPath(directory,path173.relative(path173.join(directory,".swarm"),target)),revalidatedTemp=validateSwarmPath(directory,path173.relative(path173.join(directory,".swarm"),tempPath)),revalidatedStat=fs94.lstatSync(revalidatedTemp);if(!revalidatedStat.isFile()||revalidatedStat.isSymbolicLink())throw Error("auto-review evidence temp path changed before commit");return fs94.renameSync(revalidatedTemp,safeTarget),invalidateCachedArtifact(safeTarget),safeTarget}finally{try{fs94.unlinkSync(tempPath)}catch{}}}function readAutoReviewEvidenceForPhase(directory,phase){try{let target=validateSwarmPath(directory,path173.join("evidence",String(phase),"auto-review.json")),parsed=JSON.parse(fs94.readFileSync(target,"utf8"));if(!isAutoReviewEvidence(parsed))return null;return parsed}catch{return null}}function isAutoReviewEvidence(value){if(!value||typeof value!=="object")return!1;let candidate=value;if(!(candidate.schema_version===1&&typeof candidate.timestamp==="string"&&["task_completion","phase_completion","plan_completion","manual"].includes(String(candidate.trigger))&&typeof candidate.session_id==="string"&&Boolean(candidate.scope)&&typeof candidate.scope?.hash==="string"&&typeof candidate.scope?.head_sha==="string"&&Boolean(candidate.scope?.selector)&&Boolean(candidate.scope?.completeness)&&Boolean(candidate.policy)&&(candidate.policy?.mode==="advisory"||candidate.policy?.mode==="gate")&&typeof candidate.policy?.min_confidence==="number"&&typeof candidate.policy?.structured_findings==="boolean"&&typeof candidate.policy?.validate_findings==="boolean"&&Array.isArray(candidate.findings)&&Array.isArray(candidate.blocking_finding_ids)&&typeof candidate.validation_complete==="boolean"&&Boolean(candidate.review)&&["completed","clean","error"].includes(String(candidate.review?.status))))return!1;return candidate.findings.every(isAutoReviewEvidenceFinding)}function baseFinding(finding){return{title:finding.title,body:finding.body,severity:finding.severity,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end}}function isAutoReviewEvidenceFinding(value){if(!value||typeof value!=="object")return!1;let finding=value;if(!ReviewFindingSchema.safeParse(baseFinding(finding)).success||!/^[a-f0-9]{64}$/.test(finding.finding_id)||!Number.isInteger(finding.duplicate_count)||finding.duplicate_count<1||typeof finding.anchored!=="boolean"||!["critical","high","medium","low","info"].includes(finding.effective_severity))return!1;return finding.validation===void 0||FindingValidationSchema.safeParse(finding.validation).success&&finding.validation.finding_id===finding.finding_id}function failIntegrity(code,reason){return{ok:!1,code,reason}}function readContainedReceipt(directory,receiptPath){if(!receiptPath)return null;try{let content=readReviewReceiptText(directory,receiptPath);if(content===null)return null;let parsed=JSON.parse(content);if(!parsed||typeof parsed!=="object")return null;let receipt=parsed;if(receipt.schema_version!==1||!["approved","rejected"].includes(receipt.verdict)||receipt.receipt_type!==receipt.verdict||typeof receipt.id!=="string"||typeof receipt.reviewer?.agent!=="string"||typeof receipt.scope_fingerprint?.hash!=="string"||typeof receipt.scope_fingerprint?.scope_description!=="string"||!Array.isArray(receipt.structured_findings)||!receipt.structured_findings.every((finding)=>ReviewFindingSchema.safeParse(finding).success)||!Array.isArray(receipt.finding_validations)||!receipt.finding_validations.every((validation)=>FindingValidationSchema.safeParse(validation).success))return null;return receipt}catch{return null}}function sameValidation(left,right){return left.finding_id===right.finding_id&&left.disposition===right.disposition&&left.confidence===right.confidence&&left.evidence===right.evidence}function validateAutoReviewEvidenceIntegrity(directory,evidence2,expected){if(evidence2.scope.hash!==expected.scopeHash||evidence2.phase!==expected.phase||evidence2.trigger!==expected.trigger)return failIntegrity("evidence","phase, trigger, or scope binding mismatch");if(evidence2.policy.mode!==expected.policy.mode||evidence2.policy.min_confidence!==expected.policy.min_confidence||evidence2.policy.structured_findings!==expected.policy.structured_findings||evidence2.policy.validate_findings!==expected.policy.validate_findings)return failIntegrity("evidence","policy binding mismatch");let canonicalEvidence=canonicalizeValidationCandidates(evidence2.findings);if(canonicalEvidence.length!==evidence2.findings.length||canonicalEvidence.some((canonical,index)=>{let recorded=[...evidence2.findings].sort((a,b)=>a.finding_id.localeCompare(b.finding_id))[index];return canonical.finding_id!==recorded.finding_id||canonical.duplicate_count!==recorded.duplicate_count}))return failIntegrity("evidence","finding IDs or duplicate counts are invalid");if(evidence2.findings.some((finding)=>finding.effective_severity!==(finding.confidence<expected.policy.min_confidence?"info":finding.severity)))return failIntegrity("evidence","effective finding severity does not match current policy");let derivedBlockingIds=evidence2.findings.filter((finding)=>finding.anchored&&(finding.effective_severity==="high"||finding.effective_severity==="critical")&&finding.validation?.disposition==="CONFIRMED").map((finding)=>finding.finding_id).sort(),recordedBlockingIds=[...evidence2.blocking_finding_ids].sort();if(derivedBlockingIds.length!==recordedBlockingIds.length||derivedBlockingIds.some((findingId2,index)=>findingId2!==recordedBlockingIds[index]))return failIntegrity("evidence","blocking finding IDs do not match derived confirmed findings");if(evidence2.review.status!=="completed")return evidence2.findings.length===0&&evidence2.blocking_finding_ids.length===0?{ok:!0}:failIntegrity("evidence","non-completed evidence contains findings");let receipt=readContainedReceipt(directory,evidence2.receipt_path);if(!receipt)return failIntegrity("receipt_missing","receipt is missing or malformed");if(receipt.reviewer.session_id!==evidence2.session_id||receipt.scope_fingerprint.scope_description!==`${evidence2.trigger}-review`||expected.scopeContent!==void 0&&isScopeStale(receipt,expected.scopeContent))return failIntegrity("receipt","receipt scope or session binding mismatch");let receiptCandidates=canonicalizeValidationCandidates(receipt.structured_findings??[]),evidenceById=new Map(evidence2.findings.map((finding)=>[finding.finding_id,finding]));if(receiptCandidates.length!==evidence2.findings.length||receiptCandidates.some((candidate)=>{let recorded=evidenceById.get(candidate.finding_id);return!recorded||candidate.duplicate_count!==recorded.duplicate_count||JSON.stringify(baseFinding(recorded))!==JSON.stringify(baseFinding(candidate))}))return failIntegrity("receipt","receipt finding IDs or payloads mismatch");let evidenceValidations=evidence2.findings.flatMap((finding)=>finding.validation?[finding.validation]:[]).sort((a,b)=>a.finding_id.localeCompare(b.finding_id)),receiptValidations=[...receipt.finding_validations??[]].sort((a,b)=>a.finding_id.localeCompare(b.finding_id));if(evidenceValidations.length!==receiptValidations.length||evidenceValidations.some((validation,index)=>!sameValidation(validation,receiptValidations[index])))return failIntegrity("receipt","receipt finding validations mismatch");if(receipt.receipt_type==="rejected"){let receiptById=new Map(receipt.blocking_findings.map((finding)=>[finding.finding_id,finding]));if(receiptById.size!==evidence2.findings.length)return failIntegrity("receipt","rejected receipt finding IDs mismatch");for(let finding of evidence2.findings){let recorded=receiptById.get(finding.finding_id);if(!recorded||recorded.anchor_status!==(finding.anchored?"anchored":"unanchored")||recorded.anchor_reason!==finding.anchor_rejection||recorded.effective_severity!==finding.effective_severity||recorded.validator_disposition!==finding.validation?.disposition||recorded.validator_confidence!==finding.validation?.confidence||recorded.validator_evidence!==finding.validation?.evidence)return failIntegrity("receipt","rejected receipt derived finding state mismatch")}}else{let expectedCaveats=evidence2.findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`).sort(),receiptCaveats=[...receipt.caveats??[]].sort();if(expectedCaveats.length!==receiptCaveats.length||expectedCaveats.some((caveat,index)=>caveat!==receiptCaveats[index]))return failIntegrity("receipt","approved receipt anchoring caveats mismatch")}return{ok:!0,receipt}}var init_evidence2=__esm(()=>{init_agent_output_schema();init_review_receipt();init_utils2();init_bun_compat();init_swarm_artifact_cache();init_finding_validator()});import*as fs95 from"node:fs";import*as path174 from"node:path";function scopeFreshnessMismatches(reviewed,current){let mismatches=[],compare=(field,left,right)=>{if(left!==right)mismatches.push(field)};return compare("status",reviewed.status,current.status),compare("scopeHash",reviewed.scopeHash,current.scopeHash),compare("canonicalText",reviewed.canonicalText,current.canonicalText),compare("reviewTextBytes",reviewed.reviewTextBytes,current.reviewTextBytes),compare("headSha",reviewed.headSha,current.headSha),compare("baseRef",reviewed.baseRef,current.baseRef),compare("baseSha",reviewed.baseSha,current.baseSha),compare("mergeBase",reviewed.mergeBase,current.mergeBase),compare("rangeToSha",reviewed.rangeToSha,current.rangeToSha),compare("selector",JSON.stringify(reviewed.selector),JSON.stringify(current.selector)),compare("completeness",JSON.stringify(reviewed.completeness),JSON.stringify(current.completeness)),compare("includesWorkingTree",reviewed.staleness.includesWorkingTree,current.staleness.includesWorkingTree),mismatches}function createScopeVerifier(input,reviewed,maxBytes){return async()=>{let current=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});return current.status!=="error"&&scopeFreshnessMismatches(reviewed,current).length===0}}async function stalePersistenceResult(input,maxBytes,message,modelCalls){let current=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes}),result=emptyResult3("error",`${message} Stale review artifacts were discarded and provide no current coverage.`,input.config.final_review.mode==="gate",input.config.final_review.mode==="gate"?"REVIEW_SCOPE_STALE":void 0);if(result.modelCalls=modelCalls,current.status!=="error")result.scopeHash=current.scopeHash,result.scopeComplete=current.completeness.complete,Object.assign(result,scopeResultFields(current));return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}function scopeResultFields(diff,promptRequest){if(diff.completeness.complete)return{scopeWarnings:[]};let fallback=diff.completeness.fileListFallback,promptInventory=promptRequest?.fileInventory,warnings=["Review scope was incomplete; findings cover only the supplied diff subset and must not be treated as a whole-diff verdict."];if(promptInventory&&promptInventory.omittedFiles>0)warnings.push(`Review prompt changed-file inventory included ${promptInventory.files.length} of ${promptInventory.totalFiles} file name(s); ${promptInventory.omittedFiles} name(s) were omitted to stay within the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling. The full bounded collector inventory remains in durable scope evidence.`);else if(fallback)warnings.push(`Bounded changed-file fallback lists ${fallback.files.length} file(s) and is ${fallback.complete?"complete":"itself incomplete"}.`);return{scopeWarnings:warnings,scopeFileList:promptInventory?.files??fallback?.files,scopeFileListComplete:promptInventory?.complete??fallback?.complete}}function renderReviewPrompt(input,renderedFallbackFiles,omittedFallbackFiles){let{diff}=input,exactRange=diff.selector.kind==="range",reviewTargetKind=diff.selector.kind==="range"?"exact-committed-range":diff.selector.kind==="working-tree"?"checkout-index-working-tree":"checkout-history-index-working-tree",fallback=diff.completeness.fileListFallback,promptFallbackComplete=fallback?.complete&&omittedFallbackFiles===0;return[`TASK: Review the complete ${input.trigger.replaceAll("_"," ")} diff.`,input.phase?`PHASE: ${input.phase}`:"",`REVIEW_SELECTOR: ${JSON.stringify(diff.selector)}`,`REVIEW_TARGET_KIND: ${reviewTargetKind}`,`SCOPE_HASH: ${diff.scopeHash}`,`BASE_REF: ${diff.baseRef??"none"}`,`BASE_SHA: ${diff.baseSha??"none"}`,`RESOLVED_BASE_SHA: ${diff.baseSha??"none"}`,exactRange?`RESOLVED_FROM_SHA: ${diff.baseSha??"none"}`:"",exactRange?`RESOLVED_TO_SHA: ${diff.rangeToSha??"none"}`:"",exactRange?`REVIEW_TARGET_SHA: ${diff.rangeToSha??"none"}`:"",`MERGE_BASE: ${diff.mergeBase??"none"}`,`CHECKOUT_HEAD_SHA: ${diff.headSha}`,exactRange?`CHECKOUT_MATCHES_REVIEW_TARGET: ${diff.headSha===diff.rangeToSha}`:"",`REVIEW_SCOPE_INCLUDES_WORKING_TREE: ${diff.staleness.includesWorkingTree}`,`SCOPE_COMPLETE: ${diff.completeness.complete}`,diff.completeness.complete?"":"SCOPE_WARNING: INCOMPLETE. The diff block is a bounded subset. Never describe this as a whole-diff approval or infer findings from unsupplied content.",fallback?`FILE_LIST_FALLBACK_COMPLETE: ${promptFallbackComplete}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_SOURCE_COMPLETE: ${fallback.complete}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_INCLUDED: ${renderedFallbackFiles.length}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_TOTAL: ${fallback.files.length}`:"",fallback&&omittedFallbackFiles>0?`FILE_LIST_FALLBACK_OMITTED: ${omittedFallbackFiles}`:"",fallback&&omittedFallbackFiles>0?"FILE_LIST_FALLBACK_WARNING: INCOMPLETE PROMPT INVENTORY. Some changed path names are omitted only to satisfy the isolated-session byte ceiling. Review only supplied diff content and listed names; do not infer omitted paths.":"",fallback?omittedFallbackFiles>0?`FILE_LIST_FALLBACK (${renderedFallbackFiles.length} of ${fallback.files.length} changed path(s), names only; do not infer file contents):`:`FILE_LIST_FALLBACK (${fallback.files.length} changed path(s), names only; do not infer file contents):`:"",...renderedFallbackFiles.map((file3)=>JSON.stringify(file3)),"DIFF:","```diff",diff.canonicalText,"```"].filter(Boolean).join(`
2194
- `)}function reviewRequestBytes(prompt){return Buffer.byteLength(REVIEW_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8")}function buildReviewPromptRequest(input){let fallback=input.diff.completeness.fileListFallback,allFiles=fallback?.files??[],prompt=renderReviewPrompt(input,allFiles,0),requestBytes=reviewRequestBytes(prompt);if(requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)return{prompt,requestBytes,promptByteLimit:requestBytes,fits:!0,fileInventory:fallback?{files:allFiles,totalFiles:allFiles.length,omittedFiles:0,complete:fallback.complete}:void 0};let lowerBound=0,upperBound=allFiles.length;while(lowerBound<upperBound){let candidateCount=Math.ceil((lowerBound+upperBound)/2),candidatePrompt=renderReviewPrompt(input,allFiles.slice(0,candidateCount),allFiles.length-candidateCount);if(reviewRequestBytes(candidatePrompt)<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)lowerBound=candidateCount;else upperBound=candidateCount-1}let renderedFiles=allFiles.slice(0,lowerBound),omittedFiles=allFiles.length-renderedFiles.length;return prompt=renderReviewPrompt(input,renderedFiles,omittedFiles),requestBytes=reviewRequestBytes(prompt),{prompt,requestBytes,promptByteLimit:Math.min(requestBytes,MAX_EPHEMERAL_PROMPT_BYTE_LIMIT),fits:requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT,fileInventory:fallback?{files:renderedFiles,totalFiles:allFiles.length,omittedFiles,complete:fallback.complete&&omittedFiles===0}:void 0}}function hasControlCharacter3(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedRelativePath(file3){if(file3.length===0||file3.length>500||hasControlCharacter3(file3)||/^[A-Za-z]:[\\/]/.test(file3)||file3.startsWith("\\\\")||file3.startsWith("//")||path174.isAbsolute(file3))return null;let normalized=file3.replaceAll("\\","/");if(normalized.split("/").some((segment)=>segment===".."||segment==="")||normalized.startsWith("/"))return null;return normalized.replace(/^\.\//,"")}function isWithinRoot3(root,candidate){let relative40=path174.relative(root,candidate);return relative40.length>0&&relative40!==".."&&!relative40.startsWith(`..${path174.sep}`)&&!path174.isAbsolute(relative40)}function rangesOverlap(start,end,ranges){return ranges.some((range)=>start<=range.end&&end>=range.start)}function anchorExactRangeFinding(diff,normalized,start,end){if(!diff.rangeToSha||!/^[0-9a-f]{6,64}$/i.test(diff.rangeToSha))return"exact_range_target_unavailable";let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(start,end,ranges))return"line_range_does_not_overlap_diff";let file3=diff.files.get(normalized);if(!file3?.newPath||file3.newPath!==normalized||file3.kind==="deleted")return"nonexistent_target_path";return}function anchorFinding(directory,diff,finding,minConfidence){let anchorRejection,normalized=normalizedRelativePath(finding.file);if(!diff.completeness.complete||diff.completeness.truncated)anchorRejection="incomplete_or_truncated_scope";else if(!normalized)anchorRejection="unsafe_or_absolute_path";else if(diff.selector.kind==="range")anchorRejection=anchorExactRangeFinding(diff,normalized,finding.line_start,finding.line_end);else{let root,currentPath;try{root=fs95.realpathSync(directory),currentPath=fs95.realpathSync(path174.resolve(root,...normalized.split("/")))}catch{return{...finding,file:normalized,anchored:!1,anchor_rejection:"nonexistent_current_path",effective_severity:finding.confidence<minConfidence?"info":finding.severity}}if(!isWithinRoot3(root,currentPath))anchorRejection="path_outside_project";else{let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(finding.line_start,finding.line_end,ranges))anchorRejection="line_range_does_not_overlap_diff"}}return{...finding,file:normalized??finding.file,anchored:anchorRejection===void 0,anchor_rejection:anchorRejection,effective_severity:finding.confidence<minConfidence?"info":finding.severity}}function isGateSeverity(severity){return severity==="critical"||severity==="high"}function reviewModelLabel(model){return model?`${model.providerID}/${model.modelID}`:"default"}async function dispatchReviewerWithFallback(input,prompt,timeoutMs,promptByteLimit){let models=[input.reviewerModel,...input.reviewerFallbackModels??[]],attempts=[];for(let index=0;index<models.length;index++){let result=await input.dispatcher.dispatch({directory:input.directory,parentSessionId:input.sessionID,agentName:input.reviewerAgent,model:models[index],system:REVIEW_SYSTEM_PROMPT,prompt,title:`auto review (${input.trigger})`,timeoutMs,promptByteLimit});if(attempts.push(result),telemetry.delegationEnd(input.sessionID,input.reviewerAgent,input.trigger,result.status,{...result.costFields,gate:"auto_review",retry_index:index}),result.status==="completed")return{result,attempts};let detail=result.error??result.status,taskCompletionTimeout=input.trigger==="task_completion"&&(result.status==="timeout"||/auto-review timed out/i.test(detail)),transient=result.status==="timeout"||isTransientProviderError(detail);if(taskCompletionTimeout||!transient||index===models.length-1)return{result,attempts};let nextModel=models[index+1],fromModel=reviewModelLabel(models[index]),toModel=reviewModelLabel(nextModel);telemetry.modelFallback(input.sessionID,input.reviewerAgent,fromModel,toModel,"transient_model_error"),input.injectAdvisory?.(input.sessionID,`MODEL FALLBACK: auto-review reviewer failed over to "${toModel}" (fallback ${index+1}) after a transient/quota dispatch error.`)}return{result:attempts[0],attempts}}function addCost(evidence2,dispatches){evidence2.cost.model_calls=dispatches.length,evidence2.cost.prompt_bytes=dispatches.reduce((sum,dispatch)=>sum+dispatch.promptBytes,0);for(let dispatch of dispatches){let fields=dispatch.costFields;if(evidence2.cost.tokens_input+=fields?.tokens_input??0,evidence2.cost.tokens_output+=fields?.tokens_output??0,evidence2.cost.tokens_reasoning+=fields?.tokens_reasoning??0,evidence2.cost.tokens_cache+=fields?.tokens_cache??0,typeof fields?.cost_usd==="number")evidence2.cost.cost_usd=(evidence2.cost.cost_usd??0)+fields.cost_usd,evidence2.cost.cost_source=fields.cost_source==="estimated"?"estimated":evidence2.cost.cost_source==="estimated"?"estimated":"reported"}}function baseEvidence(input,diff,status){return{schema_version:1,timestamp:new Date().toISOString(),trigger:input.trigger,session_id:input.sessionID,phase:input.phase,scope:{hash:diff.scopeHash,selector:diff.selector,head_sha:diff.headSha,base_ref:diff.baseRef,base_sha:diff.baseSha,merge_base:diff.mergeBase,range_to_sha:diff.rangeToSha,review_text_bytes:diff.reviewTextBytes,completeness:diff.completeness},policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},review:{status},findings:[],validation_complete:!0,blocking_finding_ids:[],cost:{model_calls:0,diff_bytes:diff.reviewTextBytes,prompt_bytes:0,tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0,cost_usd:null,cost_source:"unavailable"}}}function advisoryMessage(input,result){let prefix=`[AUTO-REVIEW ${input.trigger.toUpperCase()}]`,scopeWarnings=result.scopeWarnings??[];if(result.status==="error")return[`${prefix} ${result.message}`,...scopeWarnings].join(`
2194
+ `)}function reviewRequestBytes(prompt){return Buffer.byteLength(REVIEW_SYSTEM_PROMPT,"utf8")+Buffer.byteLength(prompt,"utf8")}function buildReviewPromptRequest(input){let fallback=input.diff.completeness.fileListFallback,allFiles=fallback?.files??[],prompt=renderReviewPrompt(input,allFiles,0),requestBytes=reviewRequestBytes(prompt);if(requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)return{prompt,requestBytes,promptByteLimit:requestBytes,fits:!0,fileInventory:fallback?{files:allFiles,totalFiles:allFiles.length,omittedFiles:0,complete:fallback.complete}:void 0};let lowerBound=0,upperBound=allFiles.length;while(lowerBound<upperBound){let candidateCount=Math.ceil((lowerBound+upperBound)/2),candidatePrompt=renderReviewPrompt(input,allFiles.slice(0,candidateCount),allFiles.length-candidateCount);if(reviewRequestBytes(candidatePrompt)<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT)lowerBound=candidateCount;else upperBound=candidateCount-1}let renderedFiles=allFiles.slice(0,lowerBound),omittedFiles=allFiles.length-renderedFiles.length;return prompt=renderReviewPrompt(input,renderedFiles,omittedFiles),requestBytes=reviewRequestBytes(prompt),{prompt,requestBytes,promptByteLimit:Math.min(requestBytes,MAX_EPHEMERAL_PROMPT_BYTE_LIMIT),fits:requestBytes<=MAX_EPHEMERAL_PROMPT_BYTE_LIMIT,fileInventory:fallback?{files:renderedFiles,totalFiles:allFiles.length,omittedFiles,complete:fallback.complete&&omittedFiles===0}:void 0}}function hasControlCharacter3(value){for(let index=0;index<value.length;index++){let code=value.charCodeAt(index);if(code<=31||code===127)return!0}return!1}function normalizedRelativePath(file3){if(file3.length===0||file3.length>500||hasControlCharacter3(file3)||/^[A-Za-z]:[\\/]/.test(file3)||file3.startsWith("\\\\")||file3.startsWith("//")||path174.isAbsolute(file3))return null;let normalized=file3.replaceAll("\\","/");if(normalized.split("/").some((segment)=>segment===".."||segment==="")||normalized.startsWith("/"))return null;return normalized.replace(/^\.\//,"")}function isWithinRoot3(root,candidate){let relative40=path174.relative(root,candidate);return relative40.length>0&&relative40!==".."&&!relative40.startsWith(`..${path174.sep}`)&&!path174.isAbsolute(relative40)}function rangesOverlap(start,end,ranges){return ranges.some((range)=>start<=range.end&&end>=range.start)}function anchorExactRangeFinding(diff,normalized,start,end){if(!diff.rangeToSha||!/^[0-9a-f]{6,64}$/i.test(diff.rangeToSha))return"exact_range_target_unavailable";let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(start,end,ranges))return"line_range_does_not_overlap_diff";let file3=diff.files.get(normalized);if(!file3?.newPath||file3.newPath!==normalized||file3.kind==="deleted")return"nonexistent_target_path";return}function anchorFinding(directory,diff,finding,minConfidence){let anchorRejection,normalized=normalizedRelativePath(finding.file);if(!diff.completeness.complete||diff.completeness.truncated)anchorRejection="incomplete_or_truncated_scope";else if(!normalized)anchorRejection="unsafe_or_absolute_path";else if(diff.selector.kind==="range")anchorRejection=anchorExactRangeFinding(diff,normalized,finding.line_start,finding.line_end);else{let root,currentPath;try{root=fs95.realpathSync(directory),currentPath=fs95.realpathSync(path174.resolve(root,...normalized.split("/")))}catch{return{...finding,file:normalized,anchored:!1,anchor_rejection:"nonexistent_current_path",effective_severity:finding.confidence<minConfidence?"info":finding.severity}}if(!isWithinRoot3(root,currentPath))anchorRejection="path_outside_project";else{let ranges=diff.changedLines.get(normalized);if(!ranges||!rangesOverlap(finding.line_start,finding.line_end,ranges))anchorRejection="line_range_does_not_overlap_diff"}}return{...finding,file:normalized??finding.file,anchored:anchorRejection===void 0,anchor_rejection:anchorRejection,effective_severity:finding.confidence<minConfidence?"info":finding.severity}}function isGateSeverity(severity){return severity==="critical"||severity==="high"}function reviewModelLabel(model){return model?`${model.providerID}/${model.modelID}`:"default"}async function dispatchReviewerWithFallback(input,prompt,timeoutMs,promptByteLimit){let models=[input.reviewerModel,...input.reviewerFallbackModels??[]],attempts=[];for(let index=0;index<models.length;index++){telemetry.delegationBegin(input.sessionID,input.reviewerAgent,input.trigger);let result=await input.dispatcher.dispatch({directory:input.directory,parentSessionId:input.sessionID,agentName:input.reviewerAgent,model:models[index],system:REVIEW_SYSTEM_PROMPT,prompt,title:`auto review (${input.trigger})`,timeoutMs,promptByteLimit});if(attempts.push(result),telemetry.delegationEnd(input.sessionID,input.reviewerAgent,input.trigger,result.status,{...result.costFields,gate:"auto_review",retry_index:index}),result.status==="completed")return{result,attempts};let detail=result.error??result.status,taskCompletionTimeout=input.trigger==="task_completion"&&(result.status==="timeout"||/auto-review timed out/i.test(detail)),transient=result.status==="timeout"||isTransientProviderError(detail);if(taskCompletionTimeout||!transient||index===models.length-1)return{result,attempts};let nextModel=models[index+1],fromModel=reviewModelLabel(models[index]),toModel=reviewModelLabel(nextModel);telemetry.modelFallback(input.sessionID,input.reviewerAgent,fromModel,toModel,"transient_model_error"),input.injectAdvisory?.(input.sessionID,`MODEL FALLBACK: auto-review reviewer failed over to "${toModel}" (fallback ${index+1}) after a transient/quota dispatch error.`)}return{result:attempts[0],attempts}}function addCost(evidence2,dispatches){evidence2.cost.model_calls=dispatches.length,evidence2.cost.prompt_bytes=dispatches.reduce((sum,dispatch)=>sum+dispatch.promptBytes,0);for(let dispatch of dispatches){let fields=dispatch.costFields;if(evidence2.cost.tokens_input+=fields?.tokens_input??0,evidence2.cost.tokens_output+=fields?.tokens_output??0,evidence2.cost.tokens_reasoning+=fields?.tokens_reasoning??0,evidence2.cost.tokens_cache+=fields?.tokens_cache??0,typeof fields?.cost_usd==="number")evidence2.cost.cost_usd=(evidence2.cost.cost_usd??0)+fields.cost_usd,evidence2.cost.cost_source=fields.cost_source==="estimated"?"estimated":evidence2.cost.cost_source==="estimated"?"estimated":"reported"}}function baseEvidence(input,diff,status){return{schema_version:1,timestamp:new Date().toISOString(),trigger:input.trigger,session_id:input.sessionID,phase:input.phase,scope:{hash:diff.scopeHash,selector:diff.selector,head_sha:diff.headSha,base_ref:diff.baseRef,base_sha:diff.baseSha,merge_base:diff.mergeBase,range_to_sha:diff.rangeToSha,review_text_bytes:diff.reviewTextBytes,completeness:diff.completeness},policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},review:{status},findings:[],validation_complete:!0,blocking_finding_ids:[],cost:{model_calls:0,diff_bytes:diff.reviewTextBytes,prompt_bytes:0,tokens_input:0,tokens_output:0,tokens_reasoning:0,tokens_cache:0,cost_usd:null,cost_source:"unavailable"}}}function advisoryMessage(input,result){let prefix=`[AUTO-REVIEW ${input.trigger.toUpperCase()}]`,scopeWarnings=result.scopeWarnings??[];if(result.status==="error")return[`${prefix} ${result.message}`,...scopeWarnings].join(`
2195
2195
  `);if(result.findings.length===0)return[result.scopeComplete===!1?`${prefix} No findings were reported in the reviewed subset; the scope was incomplete.`:`${prefix} No findings reported.`,...scopeWarnings].join(`
2196
2196
  `);let items=result.findings.slice(0,5).map((finding)=>{let validation=finding.validation?` ${finding.validation.disposition}`:"",anchor=finding.anchored?"":` rejected-anchor=${finding.anchor_rejection}`;return`- [${finding.effective_severity.toUpperCase()}${validation}] ${finding.file}:${finding.line_start} ${finding.title}${anchor}`});return[`${prefix} ${result.findings.length} finding(s); ${result.blockingFindings.length} confirmed blocker(s).`,...scopeWarnings,...items].join(`
2197
- `)}function emptyResult3(status,message,blocked,blockReason){return{status,blocked,blockReason,message,findings:[],blockingFindings:[],validationComplete:!1,modelCalls:0}}async function persistErrorResult(input,diff,result,error93,dispatches,promptRequest){let evidence2=baseEvidence(input,diff,"error");evidence2.review.error=error93,addCost(evidence2,dispatches);try{result.evidencePath=await _internals137.persistEvidence(input.directory,evidence2)}catch{if(input.config.final_review.mode==="gate")result.blocked=!0,result.blockReason="EVIDENCE_PERSISTENCE_FAILED"}return result.scopeHash=diff.scopeHash,result.scopeComplete=diff.completeness.complete,Object.assign(result,scopeResultFields(diff,promptRequest)),result}async function runReviewEngine(input){let gateMode=input.config.final_review.mode==="gate",maxBytes=input.trigger==="task_completion"?input.config.max_diff_kb*1024:input.config.final_review.max_diff_bytes,timeoutMs=input.trigger==="task_completion"?input.config.timeout_ms:input.config.final_review.timeout_ms,diff=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(diff.status==="error"){let result2=emptyResult3("error",`Diff collection failed: ${diff.reason}`,gateMode,gateMode?"DIFF_COLLECTION_FAILED":void 0);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}if(diff.status==="clean"){let evidence3=baseEvidence(input,diff,"clean"),evidencePath2;try{evidencePath2=await _internals137.persistEvidence(input.directory,evidence3,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before clean evidence could be committed.",0)}let blocked2=gateMode&&!evidencePath2;return{...emptyResult3("clean","Review scope is clean.",blocked2,blocked2?"EVIDENCE_PERSISTENCE_FAILED":void 0),validationComplete:!0,scopeHash:diff.scopeHash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff),evidencePath:evidencePath2}}let promptRequest=buildReviewPromptRequest({trigger:input.trigger,diff,phase:input.phase});if(input.phase!==void 0&&(input.trigger==="phase_completion"||input.trigger==="plan_completion")){let existing=_internals137.readPhaseEvidence(input.directory,input.phase),integrity=existing?validateAutoReviewEvidenceIntegrity(input.directory,existing,{scopeHash:diff.scopeHash,phase:input.phase,trigger:input.trigger,policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},scopeContent:diff.canonicalText}):void 0;if(existing?.review.status==="completed"&&existing.scope.head_sha===diff.headSha&&integrity?.ok&&integrity.receipt){let validationsById=new Map((integrity.receipt.finding_validations??[]).map((validation)=>[validation.finding_id,validation])),findings2=canonicalizeValidationCandidates(integrity.receipt.structured_findings??[]).map((candidate)=>{return{...anchorFinding(input.directory,diff,candidate,input.config.min_confidence),validation:validationsById.get(candidate.finding_id)}}),validationCandidates2=findings2.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete2=!((input.config.validate_findings||gateMode)&&validationCandidates2.length>0)||validationCandidates2.every((finding)=>finding.validation),blockingFindings2=validationCandidates2.filter((finding)=>finding.validation?.disposition==="CONFIRMED"),blocked2=gateMode&&(!diff.completeness.complete||!validationComplete2||blockingFindings2.length>0);return{status:"completed",reviewVerdict:integrity.receipt.verdict,blocked:blocked2,blockReason:blocked2?!diff.completeness.complete?"INCOMPLETE_SCOPE":!validationComplete2?"INCOMPLETE_VALIDATION":"CONFIRMED_FINDINGS":void 0,message:"Reused fresh auto-review evidence for the unchanged scope.",findings:findings2,blockingFindings:blockingFindings2,validationComplete:validationComplete2,receiptPath:existing.receipt_path,evidencePath:path174.join(input.directory,".swarm","evidence",String(input.phase),"auto-review.json"),scopeHash:existing.scope.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:existing.review.model,modelCalls:0}}}if(!promptRequest.fits){let error93=`Rendered review prompt requires ${promptRequest.requestBytes} bytes after omitting all fallback file names, exceeding the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling.`,result2=await persistErrorResult(input,diff,emptyResult3("error",`Review dispatch failed: ${error93}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),error93,[],promptRequest);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let dispatched=await dispatchReviewerWithFallback(input,promptRequest.prompt,timeoutMs,promptRequest.promptByteLimit);if(dispatched.result.status!=="completed"){let dispatchDetail=dispatched.result.error??dispatched.result.status,quotaAnnotation=isQuotaError(dispatchDetail)?" (model quota/usage limit exhausted across all configured fallbacks)":"",result2=await persistErrorResult(input,diff,emptyResult3("error",`Review dispatch failed${quotaAnnotation}: ${dispatchDetail}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),dispatchDetail,dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let parsed=parseReviewerOutput(dispatched.result.text,{structured:input.config.structured_findings});if(!parsed){let result2=await persistErrorResult(input,diff,emptyResult3("error","Reviewer returned no machine-readable verdict.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer returned no machine-readable verdict.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let legacyVerdict=[...dispatched.result.text.matchAll(/^\s*VERDICT\s*:\s*(APPROVED|REJECTED)\s*$/gim)].at(-1)?.[1]?.toLowerCase();if(legacyVerdict&&legacyVerdict!==parsed.verdict){let result2=await persistErrorResult(input,diff,emptyResult3("error","Reviewer legacy and structured verdicts disagree.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer legacy and structured verdicts disagree.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,result2}let findings=canonicalizeValidationCandidates(parsed.structuredFindings??[]).map((candidate)=>anchorFinding(input.directory,diff,candidate,input.config.min_confidence)),validationCandidates=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete=!0,validationError,allDispatches=[...dispatched.attempts];if((input.config.validate_findings||gateMode)&&validationCandidates.length>0){let validation=await runFindingValidation({dispatcher:input.dispatcher,directory:input.directory,parentSessionId:input.sessionID,agentName:input.validatorAgent,model:input.validatorModel,fallbackModels:input.validatorFallbackModels,timeoutMs:input.config.validation_timeout_ms,findings:validationCandidates,scopeContext:{selector:diff.selector,canonicalText:diff.canonicalText,scopeHash:diff.scopeHash,headSha:diff.headSha,baseRef:diff.baseRef,baseSha:diff.baseSha,mergeBase:diff.mergeBase,rangeToSha:diff.rangeToSha,completeness:diff.completeness}});validationComplete=validation.complete,validationError=validation.error;for(let[retryIndex,attempt]of validation.attempts.entries())allDispatches.push(attempt),telemetry.delegationEnd(input.sessionID,input.validatorAgent,input.trigger,attempt.status,{...attempt.costFields,gate:"finding_validation",retry_index:retryIndex});let byId=new Map(validation.validations.map((item)=>[item.finding_id,item]));findings=findings.map((finding)=>({...finding,validation:byId.get(finding.finding_id)}))}let currentScope=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(currentScope.status==="error"){let result2=emptyResult3("error",`Review scope freshness check failed after model dispatch: ${currentScope.reason}. Stale reviewer and validator output was discarded and provides no current coverage.`,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let freshnessMismatches=scopeFreshnessMismatches(diff,currentScope);if(freshnessMismatches.length>0){let staleMessage=`Review scope changed during model dispatch (${freshnessMismatches.join(", ")}). Stale reviewer and validator output was discarded and provides no current coverage.`,result2=await persistErrorResult(input,currentScope,emptyResult3("error",staleMessage,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0),staleMessage,allDispatches);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let blockingFindings=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)&&finding.validation?.disposition==="CONFIRMED"),evidence2=baseEvidence(input,diff,"completed");evidence2.review={status:"completed",output_mode:parsed.outputMode,overall_confidence:parsed.overallConfidence,model:dispatched.result.modelId,duration_ms:dispatched.result.durationMs},evidence2.findings=findings,evidence2.validation_complete=validationComplete,evidence2.validation_error=validationError,evidence2.blocking_finding_ids=blockingFindings.map((finding)=>finding.finding_id),addCost(evidence2,allDispatches);let receiptPath,receiptId;try{let receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,checkedAspects:["correctness","security","regressions"],validatedClaims:["structured review completed"],caveats:findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))}):buildRejectedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,blockingFindings:findings.map((finding)=>({location:`${finding.file}:${finding.line_start}`,summary:finding.body,line:finding.line_start,severity:finding.severity,finding_id:finding.finding_id,title:finding.title,body:finding.body,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end,effective_severity:finding.effective_severity,validator_disposition:finding.validation?.disposition,validator_confidence:finding.validation?.confidence,validator_evidence:finding.validation?.evidence,anchor_status:finding.anchored?"anchored":"unanchored",anchor_reason:finding.anchor_rejection})),evidenceReferences:findings.map((finding)=>`${finding.file}:${finding.line_start}`),passConditions:parsed.fixes,summary:`${input.trigger} review`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))});receiptId=receipt.id,receiptPath=await _internals137.persistReceipt(input.directory,receipt,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)}),evidence2.receipt_path=receiptPath}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before the review receipt could be committed.",allDispatches.length);evidence2.review.error=`receipt persistence failed: ${error93 instanceof Error?error93.message:String(error93)}`}let blocked=!1,blockReason;if(gateMode&&!diff.completeness.complete)blocked=!0,blockReason="INCOMPLETE_SCOPE";else if(gateMode&&parsed.outputMode!=="structured")blocked=!0,blockReason="INCOMPLETE_REVIEW_EVIDENCE";else if(gateMode&&!validationComplete)blocked=!0,blockReason="INCOMPLETE_VALIDATION";else if(gateMode&&!receiptPath)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED";else if(gateMode&&blockingFindings.length>0)blocked=!0,blockReason="CONFIRMED_FINDINGS";let evidencePath;try{evidencePath=await _internals137.persistEvidence(input.directory,evidence2,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(receiptPath&&receiptId)await removeReviewReceipt(input.directory,receiptPath,receiptId).catch(()=>{}),receiptPath=void 0,evidence2.receipt_path=void 0;if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before auto-review evidence could be committed.",allDispatches.length);if(gateMode)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED"}let result={status:"completed",reviewVerdict:parsed.verdict,blocked,blockReason,message:blocked?`Review gate blocked: ${blockReason}`:`Review completed with ${findings.length} finding(s).`,findings,blockingFindings,validationComplete,receiptPath,evidencePath,scopeHash:diff.scopeHash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:dispatched.result.modelId,modelCalls:allDispatches.length};return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}var REVIEW_SYSTEM_PROMPT,_internals137;var init_engine2=__esm(()=>{init_ephemeral_agent_dispatcher();init_review_receipt();init_review_receipt_collector();init_telemetry();init_provider_error_classification();init_diff_source();init_evidence2();init_finding_validator();REVIEW_SYSTEM_PROMPT=["You are an isolated repository-aware code review model.","Review only defects introduced by the supplied exact diff. Inspect the repository when needed, but never edit it.","Do not report pre-existing issues, speculation, style-only preferences, or locations outside changed hunks.","A finding must identify a concrete impact and a current-side line overlapping the diff.","If there is no finding the author would definitely want to fix, prefer an empty findings array.","","Your complete response must be at most 800 output tokens.","Emit each of these legacy fields exactly once, in this order:","VERDICT: APPROVED | REJECTED","REUSE_RE_VERIFICATION: VERIFIED | DUPLICATION_DETECTED | SKIPPED","RISK: LOW | MEDIUM | HIGH | CRITICAL","ISSUES: none (see structured findings JSON)","ACCEPTANCE_SATISFACTION: SATISFIED | PARTIAL | NOT_SATISFIED — concise evidence","TASK: task id or unknown","SKILL_COMPLIANCE: COMPLIANT | PARTIAL | VIOLATED — concise evidence","DIRECTIVE_COMPLIANCE: one line per supplied directive, or none","FIXES: required changes if rejected, otherwise none","","Then emit exactly one fenced json block and no other JSON block.","The JSON object is strict: no additional keys are allowed at the root or finding level.","The root keys are exactly findings, verdict, and overall_confidence.","findings is an array of at most 50 objects. Each finding has exactly these keys:","- title: non-empty string, at most 200 characters","- body: non-empty string, at most 2000 characters","- severity: exactly critical | high | medium | low | info","- confidence: finite number from 0 through 1","- file: non-empty repository-relative path, at most 500 characters","- line_start: integer from 1 through 10000000","- line_end: integer from line_start through 10000000","verdict is exactly APPROVED or REJECTED and must match the legacy VERDICT.","overall_confidence is a finite number from 0 through 1.","```json",'{"findings":[{"title":"Concrete defect","body":"Concrete impact and reproduction path.","severity":"high","confidence":0.95,"file":"src/example.ts","line_start":10,"line_end":10}],"verdict":"REJECTED","overall_confidence":0.95}',"```"].join(`
2197
+ `)}function emptyResult3(status,message,blocked,blockReason){return{status,blocked,blockReason,message,findings:[],blockingFindings:[],validationComplete:!1,modelCalls:0}}async function persistErrorResult(input,diff,result,error93,dispatches,promptRequest){let evidence2=baseEvidence(input,diff,"error");evidence2.review.error=error93,addCost(evidence2,dispatches);try{result.evidencePath=await _internals137.persistEvidence(input.directory,evidence2)}catch{if(input.config.final_review.mode==="gate")result.blocked=!0,result.blockReason="EVIDENCE_PERSISTENCE_FAILED"}return result.scopeHash=diff.scopeHash,result.scopeComplete=diff.completeness.complete,Object.assign(result,scopeResultFields(diff,promptRequest)),result}async function runReviewEngine(input){let gateMode=input.config.final_review.mode==="gate",maxBytes=input.trigger==="task_completion"?input.config.max_diff_kb*1024:input.config.final_review.max_diff_bytes,timeoutMs=input.trigger==="task_completion"?input.config.timeout_ms:input.config.final_review.timeout_ms,diff=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(diff.status==="error"){let result2=emptyResult3("error",`Diff collection failed: ${diff.reason}`,gateMode,gateMode?"DIFF_COLLECTION_FAILED":void 0);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}if(diff.status==="clean"){let evidence3=baseEvidence(input,diff,"clean"),evidencePath2;try{evidencePath2=await _internals137.persistEvidence(input.directory,evidence3,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before clean evidence could be committed.",0)}let blocked2=gateMode&&!evidencePath2;return{...emptyResult3("clean","Review scope is clean.",blocked2,blocked2?"EVIDENCE_PERSISTENCE_FAILED":void 0),validationComplete:!0,scopeHash:diff.scopeHash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff),evidencePath:evidencePath2}}let promptRequest=buildReviewPromptRequest({trigger:input.trigger,diff,phase:input.phase});if(input.phase!==void 0&&(input.trigger==="phase_completion"||input.trigger==="plan_completion")){let existing=_internals137.readPhaseEvidence(input.directory,input.phase),integrity=existing?validateAutoReviewEvidenceIntegrity(input.directory,existing,{scopeHash:diff.scopeHash,phase:input.phase,trigger:input.trigger,policy:{mode:input.config.final_review.mode,min_confidence:input.config.min_confidence,structured_findings:input.config.structured_findings,validate_findings:input.config.validate_findings},scopeContent:diff.canonicalText}):void 0;if(existing?.review.status==="completed"&&existing.scope.head_sha===diff.headSha&&integrity?.ok&&integrity.receipt){let validationsById=new Map((integrity.receipt.finding_validations??[]).map((validation)=>[validation.finding_id,validation])),findings2=canonicalizeValidationCandidates(integrity.receipt.structured_findings??[]).map((candidate)=>{return{...anchorFinding(input.directory,diff,candidate,input.config.min_confidence),validation:validationsById.get(candidate.finding_id)}}),validationCandidates2=findings2.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete2=!((input.config.validate_findings||gateMode)&&validationCandidates2.length>0)||validationCandidates2.every((finding)=>finding.validation),blockingFindings2=validationCandidates2.filter((finding)=>finding.validation?.disposition==="CONFIRMED"),blocked2=gateMode&&(!diff.completeness.complete||!validationComplete2||blockingFindings2.length>0);return{status:"completed",reviewVerdict:integrity.receipt.verdict,blocked:blocked2,blockReason:blocked2?!diff.completeness.complete?"INCOMPLETE_SCOPE":!validationComplete2?"INCOMPLETE_VALIDATION":"CONFIRMED_FINDINGS":void 0,message:"Reused fresh auto-review evidence for the unchanged scope.",findings:findings2,blockingFindings:blockingFindings2,validationComplete:validationComplete2,receiptPath:existing.receipt_path,evidencePath:path174.join(input.directory,".swarm","evidence",String(input.phase),"auto-review.json"),scopeHash:existing.scope.hash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:existing.review.model,modelCalls:0}}}if(!promptRequest.fits){let error93=`Rendered review prompt requires ${promptRequest.requestBytes} bytes after omitting all fallback file names, exceeding the ${MAX_EPHEMERAL_PROMPT_BYTE_LIMIT}-byte isolated-session ceiling.`,result2=await persistErrorResult(input,diff,emptyResult3("error",`Review dispatch failed: ${error93}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),error93,[],promptRequest);return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let dispatched=await dispatchReviewerWithFallback(input,promptRequest.prompt,timeoutMs,promptRequest.promptByteLimit);if(dispatched.result.status!=="completed"){let dispatchDetail=dispatched.result.error??dispatched.result.status,quotaAnnotation=isQuotaError(dispatchDetail)?" (model quota/usage limit exhausted across all configured fallbacks)":"",result2=await persistErrorResult(input,diff,emptyResult3("error",`Review dispatch failed${quotaAnnotation}: ${dispatchDetail}`,gateMode,gateMode?"REVIEW_DISPATCH_FAILED":void 0),dispatchDetail,dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let parsed=parseReviewerOutput(dispatched.result.text,{structured:input.config.structured_findings});if(!parsed){let result2=await persistErrorResult(input,diff,emptyResult3("error","Reviewer returned no machine-readable verdict.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer returned no machine-readable verdict.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let legacyVerdict=[...dispatched.result.text.matchAll(/^\s*VERDICT\s*:\s*(APPROVED|REJECTED)\s*$/gim)].at(-1)?.[1]?.toLowerCase();if(legacyVerdict&&legacyVerdict!==parsed.verdict){let result2=await persistErrorResult(input,diff,emptyResult3("error","Reviewer legacy and structured verdicts disagree.",gateMode,gateMode?"INCOMPLETE_REVIEW_EVIDENCE":void 0),"Reviewer legacy and structured verdicts disagree.",dispatched.attempts,promptRequest);return result2.modelCalls=dispatched.attempts.length,result2}let findings=canonicalizeValidationCandidates(parsed.structuredFindings??[]).map((candidate)=>anchorFinding(input.directory,diff,candidate,input.config.min_confidence)),validationCandidates=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)),validationComplete=!0,validationError,allDispatches=[...dispatched.attempts];if((input.config.validate_findings||gateMode)&&validationCandidates.length>0){let validation=await runFindingValidation({dispatcher:input.dispatcher,directory:input.directory,parentSessionId:input.sessionID,agentName:input.validatorAgent,model:input.validatorModel,fallbackModels:input.validatorFallbackModels,timeoutMs:input.config.validation_timeout_ms,findings:validationCandidates,scopeContext:{selector:diff.selector,canonicalText:diff.canonicalText,scopeHash:diff.scopeHash,headSha:diff.headSha,baseRef:diff.baseRef,baseSha:diff.baseSha,mergeBase:diff.mergeBase,rangeToSha:diff.rangeToSha,completeness:diff.completeness}});validationComplete=validation.complete,validationError=validation.error;for(let[retryIndex,attempt]of validation.attempts.entries())allDispatches.push(attempt),telemetry.delegationBegin(input.sessionID,input.validatorAgent,input.trigger),telemetry.delegationEnd(input.sessionID,input.validatorAgent,input.trigger,attempt.status,{...attempt.costFields,gate:"finding_validation",retry_index:retryIndex});let byId=new Map(validation.validations.map((item)=>[item.finding_id,item]));findings=findings.map((finding)=>({...finding,validation:byId.get(finding.finding_id)}))}let currentScope=await _internals137.collectReviewDiff({directory:input.directory,selector:input.selector,maxBytes});if(currentScope.status==="error"){let result2=emptyResult3("error",`Review scope freshness check failed after model dispatch: ${currentScope.reason}. Stale reviewer and validator output was discarded and provides no current coverage.`,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let freshnessMismatches=scopeFreshnessMismatches(diff,currentScope);if(freshnessMismatches.length>0){let staleMessage=`Review scope changed during model dispatch (${freshnessMismatches.join(", ")}). Stale reviewer and validator output was discarded and provides no current coverage.`,result2=await persistErrorResult(input,currentScope,emptyResult3("error",staleMessage,gateMode,gateMode?"REVIEW_SCOPE_STALE":void 0),staleMessage,allDispatches);return result2.modelCalls=allDispatches.length,input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result2)),result2}let blockingFindings=findings.filter((finding)=>finding.anchored&&isGateSeverity(finding.effective_severity)&&finding.validation?.disposition==="CONFIRMED"),evidence2=baseEvidence(input,diff,"completed");evidence2.review={status:"completed",output_mode:parsed.outputMode,overall_confidence:parsed.overallConfidence,model:dispatched.result.modelId,duration_ms:dispatched.result.durationMs},evidence2.findings=findings,evidence2.validation_complete=validationComplete,evidence2.validation_error=validationError,evidence2.blocking_finding_ids=blockingFindings.map((finding)=>finding.finding_id),addCost(evidence2,allDispatches);let receiptPath,receiptId;try{let receipt=parsed.verdict==="approved"?buildApprovedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,checkedAspects:["correctness","security","regressions"],validatedClaims:["structured review completed"],caveats:findings.filter((finding)=>!finding.anchored).map((finding)=>`${finding.title}: ${finding.anchor_rejection??"unanchored"}`),structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))}):buildRejectedReceipt({agent:input.reviewerAgent,sessionId:input.sessionID,scopeContent:diff.canonicalText,scopeDescription:`${input.trigger}-review`,blockingFindings:findings.map((finding)=>({location:`${finding.file}:${finding.line_start}`,summary:finding.body,line:finding.line_start,severity:finding.severity,finding_id:finding.finding_id,title:finding.title,body:finding.body,confidence:finding.confidence,file:finding.file,line_start:finding.line_start,line_end:finding.line_end,effective_severity:finding.effective_severity,validator_disposition:finding.validation?.disposition,validator_confidence:finding.validation?.confidence,validator_evidence:finding.validation?.evidence,anchor_status:finding.anchored?"anchored":"unanchored",anchor_reason:finding.anchor_rejection})),evidenceReferences:findings.map((finding)=>`${finding.file}:${finding.line_start}`),passConditions:parsed.fixes,summary:`${input.trigger} review`,structuredFindings:parsed.structuredFindings,reviewOverallConfidence:parsed.overallConfidence,findingValidations:findings.map((finding)=>finding.validation).filter((item)=>Boolean(item))});receiptId=receipt.id,receiptPath=await _internals137.persistReceipt(input.directory,receipt,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)}),evidence2.receipt_path=receiptPath}catch(error93){if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before the review receipt could be committed.",allDispatches.length);evidence2.review.error=`receipt persistence failed: ${error93 instanceof Error?error93.message:String(error93)}`}let blocked=!1,blockReason;if(gateMode&&!diff.completeness.complete)blocked=!0,blockReason="INCOMPLETE_SCOPE";else if(gateMode&&parsed.outputMode!=="structured")blocked=!0,blockReason="INCOMPLETE_REVIEW_EVIDENCE";else if(gateMode&&!validationComplete)blocked=!0,blockReason="INCOMPLETE_VALIDATION";else if(gateMode&&!receiptPath)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED";else if(gateMode&&blockingFindings.length>0)blocked=!0,blockReason="CONFIRMED_FINDINGS";let evidencePath;try{evidencePath=await _internals137.persistEvidence(input.directory,evidence2,{verifyCurrent:createScopeVerifier(input,diff,maxBytes)})}catch(error93){if(receiptPath&&receiptId)await removeReviewReceipt(input.directory,receiptPath,receiptId).catch(()=>{}),receiptPath=void 0,evidence2.receipt_path=void 0;if(error93 instanceof ReviewScopeStaleError)return stalePersistenceResult(input,maxBytes,"Review scope changed before auto-review evidence could be committed.",allDispatches.length);if(gateMode)blocked=!0,blockReason="EVIDENCE_PERSISTENCE_FAILED"}let result={status:"completed",reviewVerdict:parsed.verdict,blocked,blockReason,message:blocked?`Review gate blocked: ${blockReason}`:`Review completed with ${findings.length} finding(s).`,findings,blockingFindings,validationComplete,receiptPath,evidencePath,scopeHash:diff.scopeHash,scopeComplete:diff.completeness.complete,...scopeResultFields(diff,promptRequest),reviewModel:dispatched.result.modelId,modelCalls:allDispatches.length};return input.injectAdvisory?.(input.sessionID,advisoryMessage(input,result)),result}var REVIEW_SYSTEM_PROMPT,_internals137;var init_engine2=__esm(()=>{init_ephemeral_agent_dispatcher();init_review_receipt();init_review_receipt_collector();init_telemetry();init_provider_error_classification();init_diff_source();init_evidence2();init_finding_validator();REVIEW_SYSTEM_PROMPT=["You are an isolated repository-aware code review model.","Review only defects introduced by the supplied exact diff. Inspect the repository when needed, but never edit it.","Do not report pre-existing issues, speculation, style-only preferences, or locations outside changed hunks.","A finding must identify a concrete impact and a current-side line overlapping the diff.","If there is no finding the author would definitely want to fix, prefer an empty findings array.","","Your complete response must be at most 800 output tokens.","Emit each of these legacy fields exactly once, in this order:","VERDICT: APPROVED | REJECTED","REUSE_RE_VERIFICATION: VERIFIED | DUPLICATION_DETECTED | SKIPPED","RISK: LOW | MEDIUM | HIGH | CRITICAL","ISSUES: none (see structured findings JSON)","ACCEPTANCE_SATISFACTION: SATISFIED | PARTIAL | NOT_SATISFIED — concise evidence","TASK: task id or unknown","SKILL_COMPLIANCE: COMPLIANT | PARTIAL | VIOLATED — concise evidence","DIRECTIVE_COMPLIANCE: one line per supplied directive, or none","FIXES: required changes if rejected, otherwise none","","Then emit exactly one fenced json block and no other JSON block.","The JSON object is strict: no additional keys are allowed at the root or finding level.","The root keys are exactly findings, verdict, and overall_confidence.","findings is an array of at most 50 objects. Each finding has exactly these keys:","- title: non-empty string, at most 200 characters","- body: non-empty string, at most 2000 characters","- severity: exactly critical | high | medium | low | info","- confidence: finite number from 0 through 1","- file: non-empty repository-relative path, at most 500 characters","- line_start: integer from 1 through 10000000","- line_end: integer from line_start through 10000000","verdict is exactly APPROVED or REJECTED and must match the legacy VERDICT.","overall_confidence is a finite number from 0 through 1.","```json",'{"findings":[{"title":"Concrete defect","body":"Concrete impact and reproduction path.","severity":"high","confidence":0.95,"file":"src/example.ts","line_start":10,"line_end":10}],"verdict":"REJECTED","overall_confidence":0.95}',"```"].join(`
2198
2198
  `);_internals137={collectReviewDiff,persistEvidence:persistAutoReviewEvidence,persistReceipt:persistReviewReceipt,readPhaseEvidence:readAutoReviewEvidenceForPhase}});import*as fs96 from"node:fs";import*as path175 from"node:path";function truncateText(value,maximum=MAX_DISPLAY_TEXT){if(!value)return"";if(value.length<=maximum)return value;return`${value.slice(0,Math.max(0,maximum-16))}... [truncated]`}function formatSelector(selector){switch(selector.kind){case"default":return"default (merge-base plus working tree)";case"base":return`base ${selector.ref}`;case"range":return`range ${selector.from}${selector.operator}${selector.to}`;case"working-tree":return"working tree"}}function isPathInside(parent,candidate){let relative41=path175.relative(parent,candidate);return relative41.length>0&&relative41!==".."&&!relative41.startsWith(`..${path175.sep}`)&&!path175.isAbsolute(relative41)}function sameFileSnapshot4(left,right){return(left.dev!==0n||left.ino!==0n)&&(right.dev!==0n||right.ino!==0n)&&left.dev===right.dev&&left.ino===right.ino&&left.size===right.size&&left.mtimeNs===right.mtimeNs&&left.ctimeNs===right.ctimeNs}function readEvidence(evidencePath,directory){if(!evidencePath)return null;let swarmRoot=path175.resolve(directory,".swarm"),candidate=path175.resolve(evidencePath);if(!isPathInside(swarmRoot,candidate))return null;let descriptor;try{let statBeforeOpen=fs96.lstatSync(candidate,{bigint:!0});if(!statBeforeOpen.isFile()||statBeforeOpen.isSymbolicLink()||statBeforeOpen.size>BigInt(MAX_EVIDENCE_BYTES))return null;let canonicalBeforeOpen=fs96.realpathSync(candidate);if(!isPathInside(swarmRoot,canonicalBeforeOpen))return null;descriptor=fs96.openSync(canonicalBeforeOpen,"r");let openedBeforeRead=fs96.fstatSync(descriptor,{bigint:!0}),canonicalAfterOpen=fs96.realpathSync(candidate);if(!openedBeforeRead.isFile()||!sameFileSnapshot4(statBeforeOpen,openedBeforeRead)||!sameFileSnapshot4(openedBeforeRead,fs96.lstatSync(candidate,{bigint:!0}))||canonicalBeforeOpen!==canonicalAfterOpen||!isPathInside(swarmRoot,canonicalAfterOpen))return null;let buffer=Buffer.alloc(Number(openedBeforeRead.size)),bytesRead=fs96.readSync(descriptor,buffer,0,buffer.length,0),openedAfterRead=fs96.fstatSync(descriptor,{bigint:!0});if(bytesRead!==buffer.length||!sameFileSnapshot4(openedBeforeRead,openedAfterRead))return null;let parsed=JSON.parse(buffer.toString("utf8"));return isAutoReviewEvidence(parsed)?parsed:null}catch{return null}finally{if(descriptor!==void 0)try{fs96.closeSync(descriptor)}catch{}}}function sortedFindings(result){return[...result.findings].sort((left,right)=>{let severity=(SEVERITY_RANK[left.effective_severity]??99)-(SEVERITY_RANK[right.effective_severity]??99);if(severity!==0)return severity;let validationRank=(finding)=>finding.validation?.disposition==="CONFIRMED"?0:finding.validation?.disposition==="UNVERIFIED"?1:finding.validation?.disposition==="DISPROVED"?2:3,validation=validationRank(left)-validationRank(right);if(validation!==0)return validation;return left.finding_id.localeCompare(right.finding_id)})}function costLine(evidence2){if(!evidence2)return"Cost: unavailable (durable evidence was not readable)";let cost=evidence2.cost;return`Cost: ${cost.cost_usd===null?`unavailable (${cost.cost_source})`:`$${cost.cost_usd.toFixed(6)} (${cost.cost_source})`}; tokens ${cost.tokens_input} input / ${cost.tokens_output} output / ${cost.tokens_reasoning} reasoning / ${cost.tokens_cache} cache; prompt ${cost.prompt_bytes} bytes`}function renderHuman(result,evidence2,requestedSelector){let selector=evidence2?.scope.selector??requestedSelector,completeness=evidence2?.scope.completeness,scopeWarnings=(result.scopeWarnings??[]).slice(0,MAX_SCOPE_WARNINGS),scopeFiles=(result.scopeFileList??[]).slice(0,MAX_SCOPE_FILES2),lines=["## Swarm Review","",`Status: ${result.status}${result.blocked?` — BLOCKED (${result.blockReason??"unspecified"})`:" — advisory"}`,`Scope: ${formatSelector(selector)}; ${completeness?`${completeness.complete?"complete":"incomplete"}${completeness.truncated?", truncated":""}; ${evidence2?.scope.review_text_bytes??0} bytes`:"scope metadata unavailable"}`,`Scope hash: ${result.scopeHash??evidence2?.scope.hash??"unavailable"}`,`Validation: ${result.validationComplete?"complete":"incomplete"}`,`Reviewer model: ${result.reviewModel??evidence2?.review.model??"registered agent default / unavailable"}`,`Model calls: ${result.modelCalls}`,costLine(evidence2),`Receipt: ${result.receiptPath??evidence2?.receipt_path??"unavailable"}`,`Evidence: ${result.evidencePath??"unavailable"}`];if(scopeWarnings.length>0)lines.push("",`### Scope warnings (${result.scopeWarnings?.length??scopeWarnings.length})`,...scopeWarnings.map((warning)=>`- ${truncateText(warning)}`));if(result.scopeFileList!==void 0){let omitted=Math.max(0,result.scopeFileList.length-scopeFiles.length);if(lines.push("",`### Scope files (${result.scopeFileList.length}${result.scopeFileListComplete===!1?", fallback list may be incomplete":""})`,...scopeFiles.map((file3)=>`- ${truncateText(file3,300)}`)),omitted>0)lines.push(`- ... ${omitted} additional file(s) omitted`)}lines.push("",`### Findings (${result.findings.length})`);let findings=sortedFindings(result);if(findings.length===0)lines.push("No findings reported.");else for(let index=0;index<findings.length;index++){let finding=findings[index],validation=finding.validation?.disposition??"NOT_VALIDATED",anchor=finding.anchored?"anchored":`unanchored — ${truncateText(finding.anchor_rejection,240)||"reason unavailable"}`;if(lines.push("",`${index+1}. [${finding.effective_severity.toUpperCase()} / ${validation}] ${truncateText(finding.title,300)}`,` Location: ${truncateText(finding.file,300)}:${finding.line_start}${finding.line_end!==finding.line_start?`-${finding.line_end}`:""}`,` Anchor: ${anchor}; confidence ${finding.confidence.toFixed(2)}; duplicates ${finding.duplicate_count}`,` ${truncateText(finding.body)}`),finding.validation?.evidence)lines.push(` Validator evidence: ${truncateText(finding.validation.evidence)}`)}return lines.join(`
2199
2199
  `)}function findingForJson(finding){return{finding_id:truncateText(finding.finding_id,128),title:truncateText(finding.title),body:truncateText(finding.body),severity:finding.severity,effective_severity:finding.effective_severity,confidence:finding.confidence,file:truncateText(finding.file),line_start:finding.line_start,line_end:finding.line_end,duplicate_count:finding.duplicate_count,anchor:{anchored:finding.anchored,rejection:truncateText(finding.anchor_rejection)},validation:finding.validation?{disposition:finding.validation.disposition,confidence:finding.validation.confidence,evidence:truncateText(finding.validation.evidence)}:null}}function renderJson(result,evidence2,requestedSelector){let ranked=sortedFindings(result).map(findingForJson),scopeWarnings=(result.scopeWarnings??[]).slice(0,MAX_SCOPE_WARNINGS).map((warning)=>truncateText(warning)),scopeFiles=(result.scopeFileList??[]).slice(0,MAX_SCOPE_FILES2).map((file3)=>truncateText(file3,300)),payload={schema_version:1,command:"review",status:result.status,blocked:result.blocked,block_reason:result.blockReason??null,message:truncateText(result.message,1000),scope:{selector:evidence2?.scope.selector??requestedSelector,hash:result.scopeHash??evidence2?.scope.hash??null,complete:evidence2?.scope.completeness.complete??null,truncated:evidence2?.scope.completeness.truncated??null,skip_reasons:(evidence2?.scope.completeness.skipReasons??[]).slice(0,50).map((reason)=>({code:reason.code,path:truncateText(reason.path),detail:truncateText(reason.detail)})),review_text_bytes:evidence2?.scope.review_text_bytes??null,warnings:scopeWarnings,warnings_omitted:Math.max(0,(result.scopeWarnings?.length??0)-scopeWarnings.length),file_list:scopeFiles,file_list_complete:result.scopeFileListComplete??null,files_omitted:Math.max(0,(result.scopeFileList?.length??0)-scopeFiles.length)},validation_complete:result.validationComplete,model:result.reviewModel??evidence2?.review.model??null,model_calls:result.modelCalls,cost:evidence2?.cost??null,receipt_path:result.receiptPath??evidence2?.receipt_path??null,evidence_path:result.evidencePath??null,findings:ranked,findings_omitted:0},wrapper=(body2)=>`${JSON_OPEN_TAG}
2200
2200
  ${body2}
@@ -2422,7 +2422,7 @@ Showing full help:
2422
2422
 
2423
2423
  Showing full help:
2424
2424
 
2425
- `+fullHelp()}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation)await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl});else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path194=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path194.indexOf(current),fullChain=[name,...path194.slice(0,cycleStart>0?cycleStart:path194.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path194.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens){if(tokens.length===0)return null;if(tokens.length>=2){let compound=`${tokens[0]} ${tokens[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound)){let entry=COMMAND_REGISTRY[compound],warning=entry.deprecated?`⚠️ "/swarm ${compound}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(2),key:compound,warning}}}let key=tokens[0];if(Object.hasOwn(COMMAND_REGISTRY,key)){let entry=COMMAND_REGISTRY[key],warning=entry.deprecated?`⚠️ "/swarm ${key}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(1),key,warning}}return null}var COMMAND_REGISTRY,VALID_COMMANDS,_internals57,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_pr_workflow_gate();init_logger();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci_monitor();init_ci_simulate();init_close();init_codebase_review();init_concurrency();init_config3();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals57.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail-explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Read-only: runs independent of `turbo.epic.cochange.enabled` so it can be used as a what-if diagnostic before opting into the runtime signal.",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Epic Mode (autonomous coupling-aware parallel activation) and inspect its decisions",details:"Epic Mode is an additive overlay that composes Lean Turbo. When on, the architect follows the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → for each wave in order, dispatch one Task per taskId in the wave, ALL in one assistant message (each concurrent coder appears as a visible subagent the user can click into) → epic_record_divergence. epic_decide_phase computes the plan-wide coupling coefficient p and gates parallel promotion on p + a hot-module check + a greenfield rule. epic_plan_waves partitions promoted phases into ordered concurrent groups (waves) that respect dependency order and scope disjointness. Subcommands: on, off, status, decide (read-only what-if), last (most recent decision from durable evidence log), calibration (Capability D state: learned threshold + hot modules + recent divergent tasks). Bare /swarm epic shows status. Decision rationale persists to .swarm/evidence/epic-promotions.jsonl after every epic_decide_phase invocation.",args:"on | off | status | decide | last | calibration",category:"diagnostics",toolPolicy:"none"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. WARNING: alignment discards local changes and gitignored files. Resets agent sessions and delegation chains. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
2425
+ `+fullHelp()}async function handleModeCommandWithBundledSkills(ctx,handler,mechanicalMode){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let result=await Promise.resolve(handler(ctx.directory,ctx.args));if(/^\s*\[MODE:\s*[A-Z][A-Z0-9_-]*\b/.test(result)){if(mechanicalMode)await activatePrWorkflow(ctx.directory,ctx.sessionID,mechanicalMode,{requireCheckoutPreflight:!0})}return result}async function handlePrFeedbackCommandWithTransition(ctx){if(ctx.packageRoot)await syncBundledProjectSkillsIfMissingAsync(ctx.directory,ctx.packageRoot,!0);let parsed=parsePrFeedbackCommandInput(ctx.directory,ctx.args);if(parsed.error)return handlePrFeedbackCommand(ctx.directory,ctx.args);if(parsed.continuation)await transitionPrReviewToFeedback(ctx.directory,ctx.sessionID,{runId:parsed.continuation.runId,handoffPath:parsed.continuation.handoffPath,prUrl:parsed.prUrl});else await activatePrWorkflow(ctx.directory,ctx.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0,...parsed.prUrl?{prUrl:parsed.prUrl}:{}});return handlePrFeedbackCommand(ctx.directory,ctx.args)}function validateAliases(){let errors5=[],warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf){let target=cmdEntry.aliasOf;if(!Object.hasOwn(COMMAND_REGISTRY,target)){errors5.push(`Alias '${name}' points to non-existent command '${target}'`);continue}let visited=new Set,path194=[],current=target;while(current){let currentEntry=COMMAND_REGISTRY[current];if(!currentEntry)break;if(visited.has(current)){let cycleStart=path194.indexOf(current),fullChain=[name,...path194.slice(0,cycleStart>0?cycleStart:path194.length),current].join(" → ");errors5.push(`Circular alias detected: ${fullChain}`);break}visited.add(current),path194.push(current),current=currentEntry.aliasOf||""}}}return{valid:errors5.length===0,errors:errors5,warnings}}function validateToolPolicy(){let warnings=[];for(let[name,entry]of Object.entries(COMMAND_REGISTRY)){let cmdEntry=entry;if(cmdEntry.aliasOf||cmdEntry.subcommandOf)continue;if(cmdEntry.toolPolicy===void 0)warnings.push(`Command '${name}' has no toolPolicy field — it will not be available through the swarm_command tool. Add toolPolicy: 'agent' | 'human-only' | 'restricted' | 'none'.`)}return{valid:warnings.length===0,warnings}}function resolveCommand(tokens){if(tokens.length===0)return null;if(tokens.length>=2){let compound=`${tokens[0]} ${tokens[1]}`;if(Object.hasOwn(COMMAND_REGISTRY,compound)){let entry=COMMAND_REGISTRY[compound],warning=entry.deprecated?`⚠️ "/swarm ${compound}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(2),key:compound,warning}}}let key=tokens[0];if(Object.hasOwn(COMMAND_REGISTRY,key)){let entry=COMMAND_REGISTRY[key],warning=entry.deprecated?`⚠️ "/swarm ${key}" is deprecated. Use "/swarm ${entry.aliasOf}" instead.`:void 0;return{entry,remainingArgs:tokens.slice(1),key,warning}}return null}var COMMAND_REGISTRY,VALID_COMMANDS,_internals57,validation;var init_registry2=__esm(()=>{init_bundled_skills();init_pr_workflow_gate();init_logger();init_abort_pr_workflow();init_acknowledge_spec_drift();init_agents();init_approve_plan_critic();init_archive();init_auto_proceed();init_benchmark();init_checkpoint2();init_ci_monitor();init_ci_simulate();init_close();init_codebase_review();init_concurrency();init_config3();init_consolidate();init_context_map_stats();init_costs();init_council();init_coupling();init_curate();init_dark_matter();init_deep_dive();init_deep_research();init_design_docs();init_diagnose();init_doctor();init_epic();init_evidence();init_export();init_full_auto();init_gate_audit2();init_gate_stats2();init_handoff();init_history();init_hive_quarantine2();init_issue();init_knowledge();init_lanes();init_learning();init_link();init_loop();init_memory2();init_memory_link2();init_plan();init_post_mortem();init_pr_feedback();init_pr_monitor_status();init_pr_review();init_pr_subscribe();init_pr_unsubscribe();init_preflight();init_promote();init_qa_gates();init_reset();init_reset_session();init_retrieve();init_review();init_rollback();init_sdd();init_simulate();init_skill_opt();init_status();init_sync_plan();init_turbo();init_unlink();init_write_retro2();COMMAND_REGISTRY={"acknowledge-spec-drift":{handler:(ctx)=>handleAcknowledgeSpecDriftCommand(ctx.directory,ctx.args,ctx.source==="cli"?"cli":ctx.source==="chat"?"user":"unknown"),description:"Acknowledge that the spec has drifted from the plan and suppress further warnings",args:"",category:"diagnostics",toolPolicy:"restricted"},status:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",clashesWithNativeCcCommand:"/status",toolPolicy:"agent",toolNoArgs:!0},"context-map stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"context-map-stats":{handler:async(ctx)=>handleContextMapStatsCommand(ctx.directory),description:"Show aggregated context-capsule telemetry stats",category:"diagnostics",aliasOf:"context-map stats",deprecated:!0},"show-plan":{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (optionally filter by phase number)",category:"core",args:"[phase-number]",toolPolicy:"agent"},plan:{handler:(ctx)=>handlePlanCommand(ctx.directory,ctx.args),description:"Show current plan (deprecated alias for /swarm show-plan)",category:"core",clashesWithNativeCcCommand:"/plan",aliasOf:"show-plan",deprecated:!0},agents:{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",clashesWithNativeCcCommand:"/agents",toolPolicy:"agent",toolNoArgs:!0},help:{handler:(ctx)=>_internals57.handleHelpCommand(ctx),description:"Show help for swarm commands",category:"core",args:"[command]",details:"Without argument, shows full command listing. With argument, shows detailed help for a specific command.",toolPolicy:"agent"},history:{handler:(ctx)=>handleHistoryCommand(ctx.directory,ctx.args),description:"Show completed phases summary",category:"utility",clashesWithNativeCcCommand:"/history",toolPolicy:"agent",toolNoArgs:!0},config:{handler:(ctx)=>handleConfigCommand(ctx.directory,ctx.args),description:"Show current resolved configuration",category:"config",clashesWithNativeCcCommand:"/config",toolPolicy:"agent",toolNoArgs:!0},"config doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"config-doctor":{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",subcommandOf:"config",category:"diagnostics",aliasOf:"config doctor",deprecated:!0},"doctor tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"doctor-tools":{handler:(ctx)=>handleDoctorToolsCommand(ctx.directory,ctx.args),description:"Run tool registration coherence check",category:"diagnostics",aliasOf:"doctor tools",deprecated:!0},diagnose:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},diagnosis:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},"guardrail explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},"guardrail-explain":{handler:async(ctx)=>{let{handleGuardrailExplain:handleGuardrailExplain2}=await Promise.resolve().then(() => (init_guardrail_explain(),exports_guardrail_explain));return handleGuardrailExplain2(ctx.directory,ctx.args)},description:"Dry-run: show what the guardrails would do to a command or write target (executes nothing)",category:"diagnostics",aliasOf:"guardrail explain",deprecated:!0},"guardrail-log":{handler:async(ctx)=>{let{handleGuardrailLog:handleGuardrailLog2}=await Promise.resolve().then(() => (init_guardrail_log(),exports_guardrail_log));return handleGuardrailLog2(ctx.directory,ctx.args)},description:"Read the guardrail decision log (use --blocks-only for blocks)",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!1},preflight:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},lanes:{handler:(ctx)=>Promise.resolve(handleLanesCommand(ctx.directory,ctx.args)),description:"List active, awaiting-merge, and conflicted worktree lanes",category:"diagnostics",toolPolicy:"agent",toolNoArgs:!0},"sync-plan":{handler:(ctx)=>handleSyncPlanCommand(ctx.directory,ctx.args),description:"Ensure plan.json and plan.md are synced",args:"",category:"config",toolPolicy:"agent",toolNoArgs:!0},benchmark:{handler:(ctx)=>handleBenchmarkCommand(ctx.directory,ctx.args),description:"Show performance metrics [--cumulative] [--ci-gate] [--max-cost-usd <n>] [--gate-audit-run <id>]",args:"--cumulative, --ci-gate, --max-cost-usd <n>, --gate-audit-run <id>",category:"diagnostics",toolPolicy:"agent"},"gate-audit":{handler:(ctx)=>handleGateAuditCommand(ctx.directory,ctx.args,{packageRoot:ctx.packageRoot,dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Run the bounded Tier-1 reviewer/test/SAST/mutation/quality gate matrix",args:"--model <id>, --swarm <id>, --gates <csv>, --tasks <csv>, --runs <n>, --max-concurrency <n>, --max-retries <n>, --max-time-ms <n>, --max-cost-usd <n>, --seed <value>, --run-id <id>, --json",details:"Runs immutable curated defects only in disposable copies, records unavailable data honestly, and writes versioned results below .swarm/evidence/gate-audit/. Container tasks are unsupported until a safe array-form runner exists.",category:"diagnostics",toolPolicy:"agent"},"gate-stats":{handler:(ctx)=>handleGateStatsCommand(ctx.directory,ctx.args),description:"Show offline per-model gate catch, false-reject, retry, cost, and reviewer fallback statistics",args:"--json, --min-samples <n>",category:"diagnostics",toolPolicy:"agent"},"skill-opt":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Governed single-skill optimizer (issue #1822). Proposes, validates, and activates one allowlisted SKILL.md candidate at a time with durable lifecycle, serial control, and manual approval.",args:"plan|run|status|diff|approve|reject|rollback|history <slug> [candidateId] [--json] [--confirm] [--expected-content-hash <hash>] [--models <csv>] [--dry-run]",details:"Disabled/proposal-only by default. `run` requires skill_opt.enabled=true AND --confirm (consumes a held-out test set). approve/activate/reject/rollback are human-only and require --expected-content-hash to refuse a stale base. Stores append-only lifecycle under .swarm/evolution/skills/<slug>/<candidateId>/.",category:"utility",toolPolicy:"agent"},"skill-opt plan":{handler:(ctx)=>handleSkillOptPlan(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Propose an optimization round (dry-run; no mutation, no validation)",subcommandOf:"skill-opt",args:"<slug> [--json] [--models <csv>]",category:"utility",toolPolicy:"agent"},"skill-opt run":{handler:(ctx)=>handleSkillOptRun(ctx.directory,ctx.args,{dispatcher:ctx.evaluationModelDispatcher,parentSessionId:ctx.sessionID}),description:"Execute the optimization loop (draft→smoke→validate; held-out set is single-use so at most one validation per run). Requires skill_opt.enabled=true and --confirm.",subcommandOf:"skill-opt",args:"<slug> --confirm [--json] [--models <csv>]",category:"utility",toolPolicy:"human-only"},"skill-opt status":{handler:(ctx)=>handleSkillOptStatus(ctx.directory,ctx.args),description:"Show the current candidate lifecycle state",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt diff":{handler:(ctx)=>handleSkillOptDiff(ctx.directory,ctx.args),description:"Show baseline-vs-candidate diff summary for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},"skill-opt approve":{handler:(ctx)=>handleSkillOptApprove(ctx.directory,ctx.args),description:"Activate a pending candidate (human-only; requires --expected-content-hash)",subcommandOf:"skill-opt",args:"<slug> <candidateId> --expected-content-hash <hash> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt reject":{handler:(ctx)=>handleSkillOptReject(ctx.directory,ctx.args),description:"Record a rejection for a candidate (no active-skill mutation)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt rollback":{handler:(ctx)=>handleSkillOptRollback(ctx.directory,ctx.args),description:"Restore the pre-activation snapshot (appends a rolled_back event)",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"human-only"},"skill-opt history":{handler:(ctx)=>handleSkillOptHistory(ctx.directory,ctx.args),description:"Show the append-only lifecycle event log for a candidate",subcommandOf:"skill-opt",args:"<slug> <candidateId> [--json]",category:"utility",toolPolicy:"agent"},review:{handler:handleReviewCommand,description:"Run the independent review model against a selected Git diff",args:"--base <ref>, --range <from..to|from...to>, --working-tree, --json",details:"Collects one bounded canonical diff, dispatches the configured reviewer in a fresh read-only session, optionally validates eligible HIGH/CRITICAL findings when configured or required by gate mode, and persists the receipt and evidence. With no selector, reviews the default merge-base plus working-tree scope.",category:"diagnostics",toolPolicy:"human-only"},costs:{handler:(ctx)=>handleCostsCommand(ctx.directory,ctx.args),description:"Show per-agent and per-task token/cost telemetry [--json]",args:"--json",category:"diagnostics",toolPolicy:"agent"},learning:{handler:(ctx)=>handleLearningCommand(ctx.directory,ctx.args),description:"Show learning metrics and violation trends",args:"--json, --phase <N>",details:"Computes aggregate learning metrics from knowledge events: violation-rate trends, directive application rates, escalation frequency, per-entry ROI, and never-applied entries. Surfaces a learning summary for the curator digest.",category:"diagnostics",toolPolicy:"agent"},export:{handler:(ctx)=>handleExportCommand(ctx.directory,ctx.args),description:"Export plan and context as JSON",args:"",details:"Exports the current plan and context as JSON to stdout. Useful for piping to external tools or debugging swarm state.",category:"utility",clashesWithNativeCcCommand:"/export",toolPolicy:"agent",toolNoArgs:!0},evidence:{handler:(ctx)=>handleEvidenceCommand(ctx.directory,ctx.args),description:"Show evidence bundles [taskId]",args:"<taskId>",details:'Displays review results, test verdicts, and other evidence bundles for the given task ID (e.g., "2.1").',category:"utility",toolPolicy:"agent"},"evidence summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",toolPolicy:"agent",toolNoArgs:!0},"evidence-summary":{handler:(ctx)=>handleEvidenceSummaryCommand(ctx.directory),description:"Generate evidence summary with completion ratio and blockers",subcommandOf:"evidence",args:"",details:"Generates a summary showing completion ratio across all tasks, lists blockers, and identifies missing evidence.",category:"utility",aliasOf:"evidence summary",deprecated:!0},doctor:{handler:(ctx)=>handleDoctorCommand(ctx.directory,ctx.args),description:"Run config doctor checks",category:"diagnostics",aliasOf:"config doctor",deprecated:!0,clashesWithNativeCcCommand:"/doctor"},info:{handler:async(ctx)=>handleStatusCommand(ctx.directory,ctx.agents,ctx.sessionID),description:"Show current swarm state",category:"core",aliasOf:"status",deprecated:!0},"list-agents":{handler:(ctx)=>Promise.resolve(handleAgentsCommand(ctx.agents,void 0)),description:"List registered agents",category:"core",aliasOf:"agents",deprecated:!0},health:{handler:(ctx)=>handleDiagnoseCommand(ctx.directory,ctx.args),description:"Run health check on swarm state",category:"diagnostics",aliasOf:"diagnose",deprecated:!0},check:{handler:(ctx)=>handlePreflightCommand(ctx.directory,ctx.args),description:"Run preflight automation checks",category:"diagnostics",aliasOf:"preflight",deprecated:!0},clear:{handler:(ctx)=>handleResetSessionCommand(ctx.directory,ctx.args),description:"Clear session state while preserving plan, evidence, and knowledge",category:"utility",aliasOf:"reset-session",deprecated:!0},archive:{handler:(ctx)=>handleArchiveCommand(ctx.directory,ctx.args),description:"Archive old evidence bundles [--dry-run]",details:"Archives evidence bundles older than max_age_days (config, default 90) or beyond max_bundles cap (config, default 1000). --dry-run previews which bundles would be archived without deleting them. Applies two-tier retention: age-based first, then count-based on oldest remaining.",args:"--dry-run",category:"utility",toolPolicy:"none"},curate:{handler:(ctx)=>handleCurateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run knowledge curation and hive promotion review",args:"",category:"utility",toolPolicy:"none"},consolidate:{handler:(ctx)=>handleConsolidateCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run quota-bounded skill-improver consolidation and stage skill proposals",details:"Runs the same consolidation pass used by scheduled skill_improver trigger points: queue hardening, skill-improver proposal writing, and optional draft-skill generation. It never auto-activates skills. Use --respect-interval to obey the configured cadence instead of forcing a run.",args:"--force, --respect-interval, --evaluate",category:"utility",toolPolicy:"restricted"},coupling:{handler:(ctx)=>handleCouplingCommand(ctx.directory,ctx.args),description:"Measure plan coupling (p) and rank modules driving conflicts (Epic mode preview)",details:"Computes the coupling coefficient p = (conflicting task pairs) / (total task pairs) over the current plan, using Epic mode's combined path + co-change conflict signal. Surfaces per-module contention and a ranked decoupling roadmap. Read-only: runs independent of `turbo.epic.cochange.enabled` so it can be used as a what-if diagnostic before opting into the runtime signal.",args:"--phase <n>, --threshold <-1..1>, --min-co-changes <n>, --format markdown|json, --persist",category:"diagnostics",toolPolicy:"none"},epic:{handler:(ctx)=>handleEpicCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Toggle Epic Mode (autonomous coupling-aware parallel activation) and inspect its decisions",details:"Epic Mode is an additive overlay that composes Lean Turbo. When on, the architect follows the transparent decide-then-dispatch wave flow: declare_scope (per pending task) → epic_decide_phase → epic_plan_waves → for each wave in order, dispatch one Task per taskId in the wave, ALL in one assistant message (each concurrent coder appears as a visible subagent the user can click into) → epic_record_divergence. epic_decide_phase computes the plan-wide coupling coefficient p and gates parallel promotion on p + a hot-module check + a greenfield rule. epic_plan_waves partitions promoted phases into ordered concurrent groups (waves) that respect dependency order and scope disjointness. Subcommands: on, off, status, decide (read-only what-if), last (most recent decision from durable evidence log), calibration (Capability D state: learned threshold + hot modules + recent divergent tasks). Bare /swarm epic shows status. Decision rationale persists to .swarm/evidence/epic-promotions.jsonl after every epic_decide_phase invocation.",args:"on | off | status | decide | last | calibration",category:"diagnostics",toolPolicy:"none"},"dark-matter":{handler:(ctx)=>handleDarkMatterCommand(ctx.directory,ctx.args),description:"Detect hidden file couplings via co-change NPMI analysis",args:"--threshold <number>, --min-commits <number>",category:"diagnostics",toolPolicy:"none"},finalize:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm finalize to finalize the swarm project and archive evidence",details:"Idempotent 4-stage terminal finalization: (1) finalize writes retrospectives for in-progress phases, (2) archive creates timestamped bundle of swarm artifacts and evidence, (3) clean removes active-state files for a clean slate, (4) align performs aggressive git reset --hard to the default remote branch, discarding uncommitted changes and gitignored build artifacts (user-created untracked files are preserved); falls back to a cautious reset that preserves uncommitted changes when the aggressive path cannot proceed. WARNING: alignment discards local changes and gitignored files. Resets agent sessions, delegation chains, and active-agent mappings. Reads .swarm/close-lessons.md for explicit lessons and runs curation. Use --skill-review to run the quota-bounded skill_improver in proposal mode. Use --dry-run to preview what finalize would archive, clean, and align without taking the lock or changing anything.",args:"--prune-branches, --skill-review, --dry-run",category:"core",toolPolicy:"none"},close:{handler:(ctx)=>handleCloseCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Use /swarm close (deprecated alias) to finalize and archive swarm state",details:"Deprecated alias for /swarm finalize. Preserved for backward compatibility. Supports the same flags, including --dry-run.",args:"--prune-branches, --skill-review, --dry-run",category:"core",aliasOf:"finalize",deprecated:!0},"post-mortem":{handler:(ctx)=>handlePostMortemCommand(ctx.directory,ctx.args,{sessionID:ctx.sessionID}),description:"Run the post-mortem agent: project-end synthesis, queue triage, and final curation pass",details:"Reads .swarm/ evidence (knowledge entries, events, curator digests, proposals, retrospectives, drift reports) and produces a post-mortem report at .swarm/post-mortem-{planId}.md. Idempotent: re-runs skip if report exists unless --force is passed. Use --scope session to limit knowledge event aggregation to the current session; project scope is the default.",args:"--force, --scope session|project",category:"core",toolPolicy:"agent"},concurrency:{handler:(ctx)=>handleConcurrencyCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Manage runtime concurrency override for plan execution [set|status|reset]",args:"set <N|preset>, status, reset",details:`Sets, queries, or clears a session-scoped concurrency override for max_concurrent_tasks during plan execution.
2426
2426
  When set, the override takes precedence over the plan's locked execution_profile.max_concurrent_tasks.
2427
2427
  `+`The override is session-scoped — it does not modify the plan and is cleared on session reset.
2428
2428
  `+`
@@ -2432,7 +2432,7 @@ Subcommands:
2432
2432
  `+` concurrency status — Show effective concurrency (override, plan baseline, operational effective)
2433
2433
  `+` concurrency reset — Clear the session concurrency override
2434
2434
  `+`
2435
- `+"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 (a critic gate that intercepts phase completions and high-risk actions for review — it never plans, delegates, or executes; the architect retains all delegation duty) 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"},"abort-pr-workflow":{handler:(ctx)=>handleAbortPrWorkflowCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop [mode] [reason]",args:"[PR_REVIEW|PR_FEEDBACK] [reason...]",details:"Human-only escape hatch for an unrecoverable PR_REVIEW or PR_FEEDBACK mechanical gate. When the architect cannot reach complete_pr_workflow — for example a compound `git fetch && git checkout` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — running this clears the durable gate state for the current session and stops the auto-resume loop without depending on the trapped model. The agent itself cannot run this command; it must call the abort_pr_workflow tool (or ask you to run this command). Both paths funnel into the same fail-closed abortPrWorkflow hook, which refuses while the workflow is armed for publication or while PR workflow lanes are still in flight. When checkout preparation preserved a stash, the result instructs the caller to run prepare_pr_workflow_checkout operation=restore after the clear. An audit event is appended to .swarm/events.jsonl.",category:"utility",toolPolicy:"restricted"},"approve-plan-critic":{handler:(ctx)=>handleApprovePlanCriticCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Record a MANUAL plan-critic approval to unblock the critic_pre_plan execution gate [reason...]",args:"[reason...]",details:'Human-only escape hatch for the ratchet-tighter critic_pre_plan execution gate (issue #2012). When the critic already returned APPROVED but the mechanical snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race), an enabled critic_pre_plan gate blocks coder delegation. Running this records a manual plan_critic_gate approval snapshot so the gate unblocks, with a distinct method: "manual_override" audit marker. The agent itself cannot run this command; it must call the approve_plan_critic tool (or ask you to run this command). Both paths funnel into the same forceRecordPlanCriticApproval hook, which requires an active architect session. An audit event is appended to .swarm/events.jsonl. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost.',category:"utility",toolPolicy:"restricted"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand,"PR_REVIEW"),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: preserves dirty state, verifies and binds an exact detached PR head, reconstructs PR intent via obligation extraction cascade, computes a depth tier (S/M/L) from the bound merge-base diff, launches the base explorer wave through dispatch_lanes_async (all 6 review dimensions covered on every PR — six singleton lanes at tier L, consolidated owned_workflow_lanes partitions at tiers S/M) while the architect keeps doing non-dependent work, and polls collect_lane_results incrementally. It evaluates an exact 11-row repository-agnostic risk-family ledger, records applicable rows as MATCHED and concretely inapplicable rows as provenance-free NOT_TRIGGERED, always keeps unclassified-risk MATCHED, and dispatches micro work only for MATCHED families (dedicated lanes at tier L, consolidated sweeps at S/M). It then validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, and synthesizes only after matched coverage is closed. Failed obligations retry through the same structured async mode and exact PR head; blocking or direct-Task dispatch is not provenance-equivalent, so unclosed matched coverage leaves the review 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)=>handlePrFeedbackCommandWithTransition(ctx),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"},"ci-monitor":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCiMonitorCommand),description:"Drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge) [pr]",args:"<pr-url|owner/repo#N|N>",details:"Triggers MODE: CI_MONITOR — takes an already human-reviewed, approved PR, exhaustively researches every CI failure, fixes it end-to-end, iterates until all required checks are green (max 5 fix cycles), then merges via `gh pr merge` with no merge-strategy flag. Invoke only after human review is complete; the skill re-verifies reviewDecision: APPROVED and mergeable state before doing anything destructive. Distinct from /swarm pr-subscribe, which passively watches a PR without a merge terminal. 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:"[pr-ref] [--base <ref>]",details:"Creates a detached temporary worktree under the OS temp dir (swarm-ci-simulate) from the base — an explicit validated --base <ref> when given (stacked/release-branch PRs), otherwise the detected default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master, verified to exist) — merges the given PR ref (or the current ref), runs fixed local CI gates (typecheck, lint, build, test), then removes the worktree non-force and prunes metadata. Worktree removal is fail-closed: a blocked or dirty worktree is surfaced, never force-deleted. 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 (policy-gated; --force --reason overrides with audit)",details:'Promotes a lesson to hive knowledge directly (--category) or via an existing swarm lesson (--from-swarm), in one cross-process policy transaction (#1847). A policy failure blocks promotion unless --force --reason "<why>" is given (audited); an entry id alone is not authorization. Requires direct text or --from-swarm. An actionability floor (#1821) needs at least one predicate flag and one scope flag (see args), unless knowledge.promotion_require_actionable=false.',args:"--category <category>, --from-swarm <lesson-id>, --applies-to-tools <a,b>, --applies-to-agents <a,b>, --required-actions <a,b>, --forbidden-actions <a,b>, --verification-checks <a,b>, --force --reason <why>, <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. Before deleting, auto-backs up the state it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept) so it can be restored by copying the files back.",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. Before deleting, auto-backs up the session files it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept).",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:
2435
+ `+"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 (a critic gate that intercepts phase completions and high-risk actions for review — it never plans, delegates, or executes; the architect retains all delegation duty) 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"},"abort-pr-workflow":{handler:(ctx)=>handleAbortPrWorkflowCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop [mode] [reason]",args:"[PR_REVIEW|PR_FEEDBACK] [reason...]",details:"Human-only escape hatch for an unrecoverable PR_REVIEW or PR_FEEDBACK mechanical gate. When the architect cannot reach complete_pr_workflow — for example a compound `git fetch && git checkout` was rejected as read-only shell syntax, the PR head cannot be fetched, or the working tree is on the wrong branch — running this clears the durable gate state for the current session and stops the auto-resume loop without depending on the trapped model. The agent itself cannot run this command; it must call the abort_pr_workflow tool (or ask you to run this command). Both paths funnel into the same fail-closed abortPrWorkflow hook, which refuses while the workflow is armed for publication or while PR workflow lanes are still in flight. When checkout preparation preserved a stash, the result instructs the caller to run prepare_pr_workflow_checkout operation=restore after the clear. An audit event is appended to .swarm/events.jsonl.",category:"utility",toolPolicy:"restricted"},"approve-plan-critic":{handler:(ctx)=>handleApprovePlanCriticCommand(ctx.directory,ctx.args,ctx.sessionID),description:"Record a MANUAL plan-critic approval to unblock the critic_pre_plan execution gate [reason...]",args:"[reason...]",details:'Human-only escape hatch for the ratchet-tighter critic_pre_plan execution gate (issue #2012). When the critic already returned APPROVED but the mechanical snapshot recorder failed to persist it (verdict-format mismatch, dispatch-signal miss, or a plan.json read race), an enabled critic_pre_plan gate blocks coder delegation. Running this records a manual plan_critic_gate approval snapshot so the gate unblocks, with a distinct method: "manual_override" audit marker. The agent itself cannot run this command; it must call the approve_plan_critic tool (or ask you to run this command). Both paths funnel into the same forceRecordPlanCriticApproval hook, which requires an active architect session. An audit event is appended to .swarm/events.jsonl. Prefer re-running MODE: CRITIC-GATE first; use this only as an escape hatch when a legitimate APPROVED was lost.',category:"utility",toolPolicy:"restricted"},"pr-review":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handlePrReviewCommand,"PR_REVIEW"),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: preserves dirty state, verifies and binds an exact detached PR head, reconstructs PR intent via obligation extraction cascade, computes a depth tier (S/M/L) from the bound merge-base diff, launches the base explorer wave through dispatch_lanes_async (all 6 review dimensions covered on every PR — six singleton lanes at tier L, consolidated owned_workflow_lanes partitions at tiers S/M) while the architect keeps doing non-dependent work, and polls collect_lane_results incrementally. It evaluates an exact 11-row repository-agnostic risk-family ledger, records applicable rows as MATCHED and concretely inapplicable rows as provenance-free NOT_TRIGGERED, always keeps unclassified-risk MATCHED, and dispatches micro work only for MATCHED families (dedicated lanes at tier L, consolidated sweeps at S/M). It then validates findings through independent reviewer confirmation, applies critic challenge to HIGH/CRITICAL findings, and synthesizes only after matched coverage is closed. Failed obligations retry through the same structured async mode and exact PR head; blocking or direct-Task dispatch is not provenance-equivalent, so unclosed matched coverage leaves the review 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)=>handlePrFeedbackCommandWithTransition(ctx),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"},"ci-monitor":{handler:(ctx)=>handleModeCommandWithBundledSkills(ctx,handleCiMonitorCommand),description:"Drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge) [pr]",args:"<pr-url|owner/repo#N|N>",details:"Triggers MODE: CI_MONITOR — takes an already human-reviewed, approved PR, exhaustively researches every CI failure, fixes it end-to-end, iterates until all required checks are green (max 5 fix cycles), then merges via `gh pr merge` with no merge-strategy flag. Invoke only after human review is complete; the skill re-verifies reviewDecision: APPROVED and mergeable state before doing anything destructive. Distinct from /swarm pr-subscribe, which passively watches a PR without a merge terminal. 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:"[pr-ref] [--base <ref>]",details:"Creates a detached temporary worktree under the OS temp dir (swarm-ci-simulate) from the base — an explicit validated --base <ref> when given (stacked/release-branch PRs), otherwise the detected default remote branch (origin/HEAD, init.defaultBranch, origin/main, origin/master, verified to exist) — merges the given PR ref (or the current ref), runs fixed local CI gates (typecheck, lint, build, test), then removes the worktree non-force and prunes metadata. Worktree removal is fail-closed: a blocked or dirty worktree is surfaced, never force-deleted. 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 (policy-gated; --force --reason overrides with audit)",details:'Promotes a lesson to hive knowledge directly (--category) or via an existing swarm lesson (--from-swarm), in one cross-process policy transaction (#1847). A policy failure blocks promotion unless --force --reason "<why>" is given (audited); an entry id alone is not authorization. Requires direct text or --from-swarm. An actionability floor (#1821) needs at least one predicate flag and one scope flag (see args), unless knowledge.promotion_require_actionable=false.',args:"--category <category>, --from-swarm <lesson-id>, --applies-to-tools <a,b>, --applies-to-agents <a,b>, --required-actions <a,b>, --forbidden-actions <a,b>, --verification-checks <a,b>, --force --reason <why>, <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. Before deleting, auto-backs up the state it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept) so it can be restored by copying the files back.",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, delegation chains, and active-agent mappings. Preserves plan, evidence, and knowledge for cross-session continuity. Before deleting, auto-backs up the session files it removes to .swarm/reset-backups/<timestamp>/ (newest 5 kept).",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:
2436
2436
 
2437
2437
  `+`**Standard turbo** — ${TURBO_BYPASS_DISCLOSURE}
2438
2438
  `+`**Lean turbo** — parallel lane execution with per-lane reviewer gates and file-lock conflict detection. ${TURBO_BYPASS_DISCLOSURE}
@@ -6335,7 +6335,7 @@ ${findingText}
6335
6335
  Review before proceeding.`;injectSystemMessage(input.sessionID,message)}}}init_bun_compat();init_utils2();import*as fs135 from"node:fs";function recordSteeringConsumed(directory,directiveId){try{let eventsPath=validateSwarmPath(directory,"events.jsonl"),event={type:"steering-consumed",directiveId,timestamp:new Date().toISOString()};fs135.appendFileSync(eventsPath,`${JSON.stringify(event)}
6336
6336
  `,"utf-8")}catch{}}function createSteeringConsumedHook(directory){return safeHook(async()=>{try{let eventsPath=validateSwarmPath(directory,"events.jsonl"),content=await bunFile(eventsPath).text();if(!content.trim())return;let lines=content.trim().split(`
6337
6337
  `),directiveIds=new Set,consumedIds=new Set;for(let line of lines){if(!line.trim())continue;try{let parsed=JSON.parse(line);if(parsed.type==="steering-directive"&&parsed.directiveId)directiveIds.add(parsed.directiveId);else if(parsed.type==="steering-consumed"&&parsed.directiveId)consumedIds.add(parsed.directiveId)}catch{}}for(let directiveId of directiveIds)if(!consumedIds.has(directiveId))recordSteeringConsumed(directory,directiveId)}catch{}})}init_trajectory_logger();init_p_limit();init_knowledge_curator();init_knowledge_reinforcement();init_knowledge_store();init_knowledge_validator();init_micro_reflector();init_logger();init_candidate_queue();init_provenance();function timeoutSignal(ms){let controller=new AbortController,timer=setTimeout(()=>{controller.abort(new DOMException("The operation timed out.","TimeoutError"))},ms);return{signal:controller.signal,clear:()=>clearTimeout(timer)}}var SCREENING_TOKEN_ESTIMATE=400,SCREENING_PROMPT_CAP=1200;function unionSourceKnowledgeIds(entry,ids){let next=entry.source_knowledge_ids;for(let id of ids)next=unionInsightMarker(next,id);entry.source_knowledge_ids=next??[]}function findActiveEntryWithMarker(entries,marker){return entries.find((entry)=>isActiveSwarmKnowledgeEntry(entry)&&(entry.source_knowledge_ids??[]).includes(marker))}function buildScreeningPrompt(candidate2){return["A subagent proposed this durable procedural lesson for the shared knowledge store.","Answer with exactly one word: ADMIT or REJECT.","REJECT when the lesson is task-specific trivia, a transient environment failure, or not generalizable.","",`LESSON: ${candidate2.lesson}`,`CATEGORY: ${candidate2.category}`,`SCOPE: agents=${(candidate2.applies_to_agents??[]).join(",")} tools=${(candidate2.applies_to_tools??[]).join(",")}`].join(`
6338
- `).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;if(!deps.llmBudget)return!0;let remainingMs=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;let{signal:signal2,clear}=timeoutSignal(timeoutMs);try{let response=await deps.llmDelegate("",buildScreeningPrompt(candidate2),signal2);return!/\bREJECT\b/i.test(response??"")}finally{clear()}}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_observability();init_manager();init_prm();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal})}}init_finding_validator();init_runtime2();init_compaction_service();init_config_doctor();init_cost_accounting();init_version_check();init_state3();init_utils2();init_state2();init_bun_compat();init_logger();import{renameSync as renameSync37}from"node:fs";var TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"];function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let windows={};for(let[key,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){try{let resolvedPath=validateSwarmPath(directory,"session/state.json"),content=await bunFile(resolvedPath).text();if(!content.trim())return null;let parsed=JSON.parse(content,(key,value)=>{if(key==="__proto__"||key==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,"session/state.json.quarantine");renameSync37(resolvedPath,quarantinePath)}catch{}return null}return parsed}catch{return null}}async function rehydrateState(snapshot,directory){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear(),snapshot.toolAggregates)for(let[key,value]of Object.entries(snapshot.toolAggregates))swarmState.toolAggregates.set(key,value);if(snapshot.activeAgent)for(let[key,value]of Object.entries(snapshot.activeAgent))swarmState.activeAgent.set(key,value);if(snapshot.delegationChains)for(let[key,value]of Object.entries(snapshot.delegationChains))swarmState.delegationChains.set(key,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS)session[field.name]=field.resetValue;if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}swarmState.agentSessions.set(sessionId,session)}}async function loadSnapshot(directory){try{await buildRehydrationCache(directory);let snapshot=await readSnapshot(directory);if(snapshot!==null){await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session)}}catch{}}init_snapshot_writer();init_state2();init_telemetry();init_zod();init_config();init_agents2();init_schema();init_ephemeral_agent_dispatcher();import*as fs137 from"node:fs/promises";import*as path243 from"node:path";init_runtime2();init_state2();init_telemetry();init_provider_error_classification();init_swarm_artifact_cache();init_bun_compat();init_swarm_artifact_cache();import{rmSync as rmSync17}from"node:fs";import*as fs136 from"node:fs/promises";import*as path242 from"node:path";function leanTurboEvidenceDir(directory,phase){return path242.join(directory,".swarm","evidence",String(phase),"lean-turbo")}function validateLaneId(laneId){if(laneId.length===0)throw Error("Invalid laneId: empty string is not allowed");if(laneId.length>128)throw Error(`Invalid laneId: exceeds maximum length of 128 characters (got ${laneId.length})`);if(laneId.includes("/")||laneId.includes("\\"))throw Error(`Invalid laneId: path separators are not allowed (got "${laneId}")`);if(laneId.includes(".."))throw Error(`Invalid laneId: parent-directory references are not allowed (got "${laneId}")`);if(laneId.startsWith("/")||/^[a-zA-Z]:/i.test(laneId))throw Error(`Invalid laneId: absolute paths are not allowed (got "${laneId}")`)}function laneEvidencePath(directory,phase,laneId){validateLaneId(laneId);let expectedDir=leanTurboEvidenceDir(directory,phase),resolvedPath=path242.resolve(path242.join(expectedDir,`${laneId}.json`)),resolvedDir=path242.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path242.sep)&&resolvedPath!==resolvedDir)throw Error(`Invalid laneId: path traversal detected (got "${laneId}")`);return resolvedPath}async function atomicWriteJson(filePath,data){let content=JSON.stringify(data,null,2),dir=path242.dirname(filePath);await fs136.mkdir(dir,{recursive:!0});let tempPath=`${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content),await fs136.rename(tempPath,filePath),invalidateCachedArtifact(filePath)}catch(error93){try{rmSync17(tempPath,{force:!0})}catch{}throw error93}}function phaseEvidencePath(directory,phase){return path242.join(leanTurboEvidenceDir(directory,phase),"lean-turbo-phase.json")}async function writeLaneEvidence(directory,phase,evidence2){let targetPath=laneEvidencePath(directory,phase,evidence2.laneId);await atomicWriteJson(targetPath,evidence2)}async function writePhaseEvidence(directory,evidence2){let targetPath=phaseEvidencePath(directory,evidence2.phase);await atomicWriteJson(targetPath,evidence2)}async function readPhaseEvidence(directory,phase){let targetPath=phaseEvidencePath(directory,phase),content;try{content=await fs136.readFile(targetPath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function listLaneEvidence(directory,phase){let evidenceDir=leanTurboEvidenceDir(directory,phase),entries;try{entries=await fs136.readdir(evidenceDir)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw error93}entries.sort();let lanes=[];for(let entry of entries){if(!entry.endsWith(".json"))continue;if(entry==="lean-turbo-phase.json")continue;let filePath=path242.join(evidenceDir,entry),content;try{content=await fs136.readFile(filePath,"utf-8")}catch{continue}try{let parsed=JSON.parse(content);lanes.push(parsed)}catch{}}return lanes}init_state4();var DEFAULT_CONFIG2={reviewerAgent:"",timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,requireDiffSummary:!1};function resolveDefaultReviewerAgent(generatedAgentNames,activeAgentName){return resolveAgentForActiveSwarm(generatedAgentNames,"reviewer",activeAgentName)}function resolveLegacyReviewerModelConfig(agentName,config3){if(config3?.dispatcher||config3?.agentModelRegistry)return;let agentBaseName=stripKnownSwarmPrefix(agentName),swarmId=agentBaseName!==agentName?agentName.slice(0,agentName.length-agentBaseName.length-1):void 0;return{agentBaseName,swarmAgents:getSwarmAgents(swarmId)}}async function compileReviewPackage(directory,phase,sessionID,requireDiffSummary){let lanes=await listLaneEvidence(directory,phase),persisted=_internals181.readPersisted?.(directory)??null;if(persisted){let matchingRunState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){matchingRunState=sessionState;break}if(!matchingRunState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){matchingRunState=sessionState;break}}if(matchingRunState?.lanes&&matchingRunState.lanes.length>0){let evidenceLaneIds=new Set(lanes.map((l)=>l.laneId)),missingLanes=matchingRunState.lanes.filter((l)=>(l.status==="completed"||l.status==="failed")&&!evidenceLaneIds.has(l.laneId));if(missingLanes.length>0)throw Error(`Lane evidence missing for ${missingLanes.length} lane(s): ${missingLanes.map((l)=>l.laneId).join(", ")}. Run lane execution before review.`)}}let phaseEvidence=await readPhaseEvidence(directory,phase),filesChangedSet=new Set;for(let lane of lanes)for(let file3 of lane.files)filesChangedSet.add(file3);let completedLanes=lanes.filter((l)=>l.status==="completed").length,failedLanes=lanes.filter((l)=>l.status==="failed").length,laneSummaries=lanes.map((lane)=>({laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:lane.status,agent:lane.agent})),degradedTasks=phaseEvidence?.degradedTasks??[],pendingDegraded=degradedTasks.filter((dt)=>!lanes.some((l)=>l.taskIds.includes(dt.taskId)&&l.status==="completed")).length,buildStatus="unknown";if(phaseEvidence?.status==="completed")buildStatus=failedLanes===0?"passed":"failed";else if(phaseEvidence?.status==="failed")buildStatus="failed";let pkg={phase,sessionID,laneSummaries,filesChanged:[...filesChangedSet],testResults:{totalLanes:lanes.length,completedLanes,failedLanes},buildStatus,degradationSummary:{totalDegraded:degradedTasks.length,resolvedDegraded:degradedTasks.length-pendingDegraded,pendingDegraded}};if(phaseEvidence?.validationArtifacts)pkg.validationArtifacts=phaseEvidence.validationArtifacts;if(requireDiffSummary){if(!phaseEvidence?.integratedDiffSummary)throw Error(`Integrated diff summary is required for phase ${phaseEvidence?.phase??"unknown"} but missing. Run the review step with diff evidence generation enabled.`);pkg.integratedDiffSummary=phaseEvidence.integratedDiffSummary}return pkg}function parseReviewerVerdict(responseText){let verdictMatch=responseText.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED)/);if(!verdictMatch)return null;let verdict=verdictMatch[1],lines=responseText.split(`
6338
+ `).slice(0,SCREENING_PROMPT_CAP)}async function screenCandidate(candidate2,deps){let perCandidateMs=deps.llmTimeoutMs??0;if(!deps.llmDelegate||perCandidateMs<=0||!deps.sessionID)return!0;if(!deps.llmBudget)return!0;let remainingMs=deps.remainingBudgetMs?.()??Number.POSITIVE_INFINITY,timeoutMs=Math.min(perCandidateMs,Math.max(0,remainingMs));if(timeoutMs<=0)return!0;if(!reserveLlmBudget(deps.sessionID,SCREENING_TOKEN_ESTIMATE,deps.llmBudget))return!0;let{signal:signal2,clear}=timeoutSignal(timeoutMs);try{let response=await deps.llmDelegate("",buildScreeningPrompt(candidate2),signal2);return!/\bREJECT\b/i.test(response??"")}finally{clear()}}async function admitCandidate(directory,candidate2,deps){let candidateId2=resolveInsightCandidateId(candidate2),marker=insightAdmissionMarker(candidateId2),now2=deps.now??(()=>Date.now());if(!validateActionableFields({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks,triggers:candidate2.triggers,directive_priority:candidate2.directive_priority}).valid)return{outcome:"rejected",reason:"invalid_shape",marker};let actionability=validateActionability({applies_to_agents:candidate2.applies_to_agents,applies_to_tools:candidate2.applies_to_tools,required_actions:candidate2.required_actions,forbidden_actions:candidate2.forbidden_actions,verification_checks:candidate2.verification_checks});if(!actionability.actionable)return{outcome:"rejected",reason:actionability.reason??"unactionable",marker};if(!await screenCandidate(candidate2,deps))return{outcome:"rejected",reason:"screened_out",marker};let provenance=stampLearningProvenance({mechanism:candidate2.source?.kind==="prm_pattern"?"prm_pattern":"micro_reflection",sourceKnowledgeIds:[marker],sourceTaskIds:candidate2.source?.task_id?[candidate2.source.task_id]:[],sourceEvidenceRefs:candidate2.source_refs??[]},{sessionId:deps.sessionID,agentRole:candidate2.source?.agent,producedAt:new Date(now2()).toISOString()}),knowledgePath=(deps.resolveKnowledgePath??resolveSwarmKnowledgePath)(directory),entry=insightCandidateToEntry(candidate2,deps.projectName,deps.phaseNumber,deps.knowledgeConfig);if(unionSourceKnowledgeIds(entry,provenance.sourceKnowledgeIds),provenance.sourceEvidenceRefs.length>0){let refs=new Set([...entry.source_refs??[],...provenance.sourceEvidenceRefs]);entry.source_refs=[...refs]}let outcome="rejected",reason="no_change",entryId;if(await transactKnowledge(knowledgePath,(current)=>{if(findActiveEntryWithMarker(current,marker))return outcome="rejected",reason="already_admitted",null;let duplicate=findActiveSwarmNearDuplicate(entry.lesson,current,deps.knowledgeConfig.dedup_threshold);if(duplicate){let result=reinforceSwarmKnowledgeEntry(duplicate,{phase_number:deps.phaseNumber,confirmed_at:new Date(now2()).toISOString(),project_name:deps.projectName});return unionSourceKnowledgeIds(duplicate,[marker]),outcome="reinforced",reason=result.reason,entryId=duplicate.id,current}return current.push(entry),outcome="admitted",reason=void 0,entryId=entry.id,current}),outcome!=="rejected")deps.onKnowledgeChanged?.();return{outcome,reason,entryId,marker,provenance}}async function realtimeAdmissionAfter(directory,input,config3,resolveDeps){if(!isTaskTool(input.tool))return;if(!config3?.enabled)return;let sessionID=typeof input.sessionID==="string"&&input.sessionID.length>0?input.sessionID:void 0;if(!sessionID)return;if(getQueueDepth(sessionID)===0)return;let deps=await resolveDeps();return drainSessionQueue(directory,sessionID,config3,deps)}function emptySummary(){return{attempted:0,admitted:0,reinforced:0,rejected:0,deferred:0,failed:0,retries:0}}async function drainSessionQueue(directory,sessionID,config3,deps){let summary=emptySummary();if(!config3.enabled)return summary;let now2=deps.now??(()=>Date.now()),stats2=getQueueStats(sessionID);if(stats2.depth===0)return summary;let velocity=computeArrivalVelocity(stats2,now2()),size=computeDrainSize(stats2.depth,velocity,{minDrain:config3.min_drain,maxDrain:config3.max_drain,drainDepthFactor:config3.drain_depth_factor,drainVelocityFactor:config3.drain_velocity_factor});if(size<=0)return summary;let batch=takeDrainBatch(sessionID,size);if(batch.length===0)return summary;summary.attempted=batch.length;let startedAt=now2(),wallTimeMs=Math.max(0,Number(config3.max_drain_wall_time_ms)||0),deadline=wallTimeMs>0?startedAt+wallTimeMs:Number.POSITIVE_INFINITY,budgetExhausted=()=>now2()>=deadline,maxRetries=Math.max(0,Math.floor(Number(config3.max_retries_per_candidate)||0)),limit=pLimit(Math.max(1,Math.floor(Number(config3.max_concurrent_admissions)||1))),admissionDeps={...deps,sessionID,llmTimeoutMs:config3.max_llm_calls_per_session>0?deps.llmTimeoutMs??config3.per_candidate_llm_timeout_ms:0,llmBudget:deps.llmBudget??{maxLlmCallsPerSession:config3.max_llm_calls_per_session,maxTokensPerSession:config3.max_tokens_per_session},remainingBudgetMs:()=>deadline-now2()},deferOrAbandon=(item)=>{if(item.attempts>=MAX_CANDIDATE_DRAIN_ATTEMPTS){summary.failed++,warn(`[learning-admission] candidate abandoned after ${item.attempts} drain attempt(s) without completing`);return}requeueCandidate(sessionID,item,{maxQueueSize:config3.max_queue_size}),summary.deferred++};return await Promise.all(batch.map((item)=>limit(async()=>{if(budgetExhausted()){deferOrAbandon(item);return}for(let attempt=0;;attempt++)try{let result=await admitCandidate(directory,item.candidate,admissionDeps);if(result.outcome==="admitted")summary.admitted++;else if(result.outcome==="reinforced")summary.reinforced++;else summary.rejected++;return}catch(err){if(attempt>=maxRetries){warn(`[learning-admission] candidate failed after ${attempt+1} attempt(s): ${isAbortError(err)?"cancelled":err instanceof Error?err.message:String(err)}`),deferOrAbandon(item);return}if(summary.retries++,recordRetry(sessionID),budgetExhausted()){deferOrAbandon(item);return}}}))),summary}init_memory();init_observability();init_manager();init_prm();init_ephemeral_agent_dispatcher();function createReviewModelDispatcher(client){return{dispatch:(request)=>dispatchEphemeralAgent({client,directory:request.directory,parentSessionId:request.parentSessionId,agentName:request.agentName,model:request.model,system:request.system,prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:request.title,timeoutMs:request.timeoutMs&&request.timeoutMs>0?request.timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,promptByteLimit:request.promptByteLimit,responseByteLimit:request.responseByteLimit,abortSignal:request.abortSignal})}}init_finding_validator();init_runtime2();init_compaction_service();init_config_doctor();init_cost_accounting();init_version_check();init_state3();init_utils2();init_state2();init_bun_compat();init_logger();import{renameSync as renameSync37}from"node:fs";var TRANSIENT_SESSION_FIELDS=[{name:"revisionLimitHit",resetValue:!1},{name:"coderRevisions",resetValue:0},{name:"selfFixAttempted",resetValue:!1},{name:"lastGateFailure",resetValue:null},{name:"architectWriteCount",resetValue:0},{name:"selfCodingWarnedAtCount",resetValue:0},{name:"pendingAdvisoryMessages",resetValue:[]},{name:"model_fallback_index",resetValue:0},{name:"modelFallbackExhausted",resetValue:!1},{name:"scopeViolationDetected",resetValue:!1},{name:"delegationActive",resetValue:!1},{name:"autoProceedOverride",resetValue:void 0},{name:"autoProceedNudgeDone",resetValue:void 0}],VALID_TASK_WORKFLOW_STATES=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","rework_required","complete","blocked","closed"];function deserializeTaskWorkflowStates(raw){let m=new Map;if(!raw||typeof raw!=="object")return m;for(let[taskId,stateVal]of Object.entries(raw))if(VALID_TASK_WORKFLOW_STATES.includes(stateVal))m.set(taskId,stateVal);return m}function deserializeModifiedFilesByTask(raw){let entries=new Map;if(!raw||typeof raw!=="object")return entries;let serializedEntries=Object.entries(raw);if(serializedEntries.length>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS)return entries;for(let[taskId,files]of serializedEntries){if(!taskId.trim()||!Array.isArray(files))continue;let validFiles=files.filter((file3)=>typeof file3==="string"&&file3.length>0);entries.set(taskId,[...new Set(validFiles)])}return entries}function deserializeAgentSession(s){let lastGateFailure=s.lastGateFailure?{tool:s.lastGateFailure.tool,taskId:s.lastGateFailure.taskId,timestamp:s.lastGateFailure.timestamp,...typeof s.lastGateFailure.code==="string"&&/^[A-Z][A-Z0-9_]{0,63}$/.test(s.lastGateFailure.code)&&{code:s.lastGateFailure.code}}:null,taskWorkflowStates=deserializeTaskWorkflowStates(s.taskWorkflowStates),modifiedFilesByTask=deserializeModifiedFilesByTask(s.modifiedFilesByTask),gateLog=new Map;if(s.gateLog)for(let[taskId,gates]of Object.entries(s.gateLog))gateLog.set(taskId,new Set(gates??[]));let reviewerCallCount=new Map;if(s.reviewerCallCount)for(let[phase,count]of Object.entries(s.reviewerCallCount)){let numPhase=Number(phase);if(Number.isFinite(numPhase))reviewerCallCount.set(numPhase,count)}let partialGateWarningsIssuedForTask=new Set(s.partialGateWarningsIssuedForTask??[]),completionGateWarnedForTask=new Set(s.completionGateWarnedForTask??[]),catastrophicPhaseWarnings=new Set(s.catastrophicPhaseWarnings??[]),phaseAgentsDispatched=new Set(s.phaseAgentsDispatched??[]),lastCompletedPhaseAgentsDispatched=new Set(s.lastCompletedPhaseAgentsDispatched??[]),stageBCompletion=new Map;if(s.stageBCompletion)for(let[taskId,agents]of Object.entries(s.stageBCompletion))stageBCompletion.set(taskId,new Set(agents));let windows={};for(let[key,win]of Object.entries(s.windows??{})){if(!win||typeof win!=="object")continue;windows[key]={...win,transientRetryCount:"transientRetryCount"in win?win.transientRetryCount??0:0}}return{agentName:s.agentName,lastToolCallTime:s.lastToolCallTime,lastAgentEventTime:s.lastAgentEventTime,delegationActive:s.delegationActive,activeInvocationId:s.activeInvocationId,lastInvocationIdByAgent:s.lastInvocationIdByAgent??{},windows,lastCompactionHint:s.lastCompactionHint??0,architectWriteCount:s.architectWriteCount??0,lastCoderDelegationTaskId:s.lastCoderDelegationTaskId??null,currentTaskId:s.currentTaskId??null,turboMode:s.turboMode??!1,turboStrategy:s.turboStrategy==="lean"||s.turboStrategy==="standard"?s.turboStrategy:void 0,leanTurboActive:s.leanTurboActive??!1,leanTurboCurrentPhase:typeof s.leanTurboCurrentPhase==="number"?s.leanTurboCurrentPhase:void 0,epicModeActive:s.epicModeActive??!1,gateLog,reviewerCallCount,lastGateFailure,partialGateWarningsIssuedForTask,completionGateWarnedForTask,selfFixAttempted:s.selfFixAttempted??!1,selfCodingWarnedAtCount:s.selfCodingWarnedAtCount??0,catastrophicPhaseWarnings,lastPhaseCompleteTimestamp:s.lastPhaseCompleteTimestamp??0,lastPhaseCompletePhase:s.lastPhaseCompletePhase??0,phaseAgentsDispatched,lastCompletedPhaseAgentsDispatched,qaSkipCount:s.qaSkipCount??0,qaSkipTaskIds:s.qaSkipTaskIds??[],taskWorkflowStates,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:s.scopeViolationDetected,modifiedFilesByTask,modifiedFilesThisCoderTask:s.currentTaskId&&s.currentTaskId.trim()!==""&&modifiedFilesByTask.has(s.currentTaskId)?[...modifiedFilesByTask.get(s.currentTaskId)??[]]:[],loopDetectionWindow:[],pendingAdvisoryMessages:s.pendingAdvisoryMessages??[],model_fallback_index:s.model_fallback_index??0,modelFallbackExhausted:s.modelFallbackExhausted??!1,coderRevisions:s.coderRevisions??0,revisionLimitHit:s.revisionLimitHit??!1,fullAutoMode:s.fullAutoMode??!1,fullAutoInteractionCount:s.fullAutoInteractionCount??0,fullAutoDeadlockCount:s.fullAutoDeadlockCount??0,fullAutoLastQuestionHash:s.fullAutoLastQuestionHash??null,maxConcurrencyOverride:typeof s.maxConcurrencyOverride==="number"?Math.min(64,Math.max(1,s.maxConcurrencyOverride)):void 0,autoProceedOverride:s.autoProceedOverride,autoProceedNudgeDone:s.autoProceedNudgeDone,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,executionEpisodeArmed:!1,sessionRehydratedAt:s.sessionRehydratedAt??0,stageBCompletion,prSubscriptions:new Map,cachedCohortId:typeof s.cachedCohortId==="string"?s.cachedCohortId:void 0,lastObservedModel:typeof s.lastObservedModel==="string"?s.lastObservedModel:void 0,lastObservedProviderID:typeof s.lastObservedProviderID==="string"?s.lastObservedProviderID:void 0}}async function readSnapshot(directory){try{let resolvedPath=validateSwarmPath(directory,"session/state.json"),content=await bunFile(resolvedPath).text();if(!content.trim())return null;let parsed=JSON.parse(content,(key,value)=>{if(key==="__proto__"||key==="constructor")return;return value});if(parsed.version!==1&&parsed.version!==2&&parsed.version!==3){try{let quarantinePath=validateSwarmPath(directory,"session/state.json.quarantine");renameSync37(resolvedPath,quarantinePath)}catch{}return null}return parsed}catch{return null}}async function rehydrateState(snapshot,directory){if(swarmState.pendingRehydrations.size>0)await Promise.allSettled([...swarmState.pendingRehydrations]);if(swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.agentSessions.clear(),snapshot.toolAggregates)for(let[key,value]of Object.entries(snapshot.toolAggregates))swarmState.toolAggregates.set(key,value);let now2=Date.now();if(snapshot.agentSessions)for(let[sessionId,serializedSession]of Object.entries(snapshot.agentSessions)){if(!serializedSession||typeof serializedSession!=="object"||typeof serializedSession.agentName!=="string"||typeof serializedSession.lastToolCallTime!=="number"||typeof serializedSession.delegationActive!=="boolean"){log(`[snapshot-reader] Skipping malformed session ${sessionId}: missing required fields (agentName, lastToolCallTime, delegationActive)`);continue}let session=deserializeAgentSession(serializedSession);if(session.taskWorkflowStates=new Map,session.taskWorkflowCache=new Map,session.stageBCompletion=new Map,session.lastToolCallTime=now2,session.lastAgentEventTime=now2,session.sessionRehydratedAt=now2,session.windows)for(let window2 of Object.values(session.windows))window2.startedAtMs=now2,window2.lastSuccessTimeMs=now2,window2.hardLimitHit=!1,window2.toolCalls=0,window2.consecutiveErrors=0,window2.recentToolCalls=[],window2.warningIssued=!1,window2.warningReason="";for(let field of TRANSIENT_SESSION_FIELDS)session[field.name]=field.resetValue;if(session.fullAutoMode){let runStillActive=!1;if(directory)try{runStillActive=loadFullAutoRunState(directory,sessionId)?.status==="running"}catch{runStillActive=!1}if(!runStillActive)session.fullAutoMode=!1}swarmState.agentSessions.set(sessionId,session)}if(snapshot.activeAgent){for(let[key,value]of Object.entries(snapshot.activeAgent))if(swarmState.agentSessions.has(key))swarmState.activeAgent.set(key,value)}if(snapshot.delegationChains){for(let[key,value]of Object.entries(snapshot.delegationChains))if(swarmState.agentSessions.has(key))swarmState.delegationChains.set(key,value)}}async function loadSnapshot(directory){try{await buildRehydrationCache(directory);let snapshot=await readSnapshot(directory);if(snapshot!==null){await rehydrateState(snapshot,directory);for(let session of swarmState.agentSessions.values())applyRehydrationCache(session)}}catch{}}init_snapshot_writer();init_state2();init_telemetry();init_zod();init_config();init_agents2();init_schema();init_ephemeral_agent_dispatcher();import*as fs137 from"node:fs/promises";import*as path243 from"node:path";init_runtime2();init_state2();init_telemetry();init_provider_error_classification();init_swarm_artifact_cache();init_bun_compat();init_swarm_artifact_cache();import{rmSync as rmSync17}from"node:fs";import*as fs136 from"node:fs/promises";import*as path242 from"node:path";function leanTurboEvidenceDir(directory,phase){return path242.join(directory,".swarm","evidence",String(phase),"lean-turbo")}function validateLaneId(laneId){if(laneId.length===0)throw Error("Invalid laneId: empty string is not allowed");if(laneId.length>128)throw Error(`Invalid laneId: exceeds maximum length of 128 characters (got ${laneId.length})`);if(laneId.includes("/")||laneId.includes("\\"))throw Error(`Invalid laneId: path separators are not allowed (got "${laneId}")`);if(laneId.includes(".."))throw Error(`Invalid laneId: parent-directory references are not allowed (got "${laneId}")`);if(laneId.startsWith("/")||/^[a-zA-Z]:/i.test(laneId))throw Error(`Invalid laneId: absolute paths are not allowed (got "${laneId}")`)}function laneEvidencePath(directory,phase,laneId){validateLaneId(laneId);let expectedDir=leanTurboEvidenceDir(directory,phase),resolvedPath=path242.resolve(path242.join(expectedDir,`${laneId}.json`)),resolvedDir=path242.resolve(expectedDir);if(!resolvedPath.startsWith(resolvedDir+path242.sep)&&resolvedPath!==resolvedDir)throw Error(`Invalid laneId: path traversal detected (got "${laneId}")`);return resolvedPath}async function atomicWriteJson(filePath,data){let content=JSON.stringify(data,null,2),dir=path242.dirname(filePath);await fs136.mkdir(dir,{recursive:!0});let tempPath=`${filePath}.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`;try{await bunWrite(tempPath,content),await fs136.rename(tempPath,filePath),invalidateCachedArtifact(filePath)}catch(error93){try{rmSync17(tempPath,{force:!0})}catch{}throw error93}}function phaseEvidencePath(directory,phase){return path242.join(leanTurboEvidenceDir(directory,phase),"lean-turbo-phase.json")}async function writeLaneEvidence(directory,phase,evidence2){let targetPath=laneEvidencePath(directory,phase,evidence2.laneId);await atomicWriteJson(targetPath,evidence2)}async function writePhaseEvidence(directory,evidence2){let targetPath=phaseEvidencePath(directory,evidence2.phase);await atomicWriteJson(targetPath,evidence2)}async function readPhaseEvidence(directory,phase){let targetPath=phaseEvidencePath(directory,phase),content;try{content=await fs136.readFile(targetPath,"utf-8")}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return null;throw error93}try{return JSON.parse(content)}catch{return null}}async function listLaneEvidence(directory,phase){let evidenceDir=leanTurboEvidenceDir(directory,phase),entries;try{entries=await fs136.readdir(evidenceDir)}catch(error93){let code=error93.code;if(code==="ENOENT"||code==="ENOTDIR")return[];throw error93}entries.sort();let lanes=[];for(let entry of entries){if(!entry.endsWith(".json"))continue;if(entry==="lean-turbo-phase.json")continue;let filePath=path242.join(evidenceDir,entry),content;try{content=await fs136.readFile(filePath,"utf-8")}catch{continue}try{let parsed=JSON.parse(content);lanes.push(parsed)}catch{}}return lanes}init_state4();var DEFAULT_CONFIG2={reviewerAgent:"",timeoutMs:DEFAULT_EPHEMERAL_TIMEOUT_MS,requireDiffSummary:!1};function resolveDefaultReviewerAgent(generatedAgentNames,activeAgentName){return resolveAgentForActiveSwarm(generatedAgentNames,"reviewer",activeAgentName)}function resolveLegacyReviewerModelConfig(agentName,config3){if(config3?.dispatcher||config3?.agentModelRegistry)return;let agentBaseName=stripKnownSwarmPrefix(agentName),swarmId=agentBaseName!==agentName?agentName.slice(0,agentName.length-agentBaseName.length-1):void 0;return{agentBaseName,swarmAgents:getSwarmAgents(swarmId)}}async function compileReviewPackage(directory,phase,sessionID,requireDiffSummary){let lanes=await listLaneEvidence(directory,phase),persisted=_internals181.readPersisted?.(directory)??null;if(persisted){let matchingRunState=null;for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"&&sessionState.sessionID===sessionID){matchingRunState=sessionState;break}if(!matchingRunState&&sessionID===void 0){for(let sessionState of Object.values(persisted.sessions))if(typeof sessionState==="object"&&sessionState!==null&&sessionState.status==="running"&&sessionState.phase===phase&&sessionState.strategy==="lean"){matchingRunState=sessionState;break}}if(matchingRunState?.lanes&&matchingRunState.lanes.length>0){let evidenceLaneIds=new Set(lanes.map((l)=>l.laneId)),missingLanes=matchingRunState.lanes.filter((l)=>(l.status==="completed"||l.status==="failed")&&!evidenceLaneIds.has(l.laneId));if(missingLanes.length>0)throw Error(`Lane evidence missing for ${missingLanes.length} lane(s): ${missingLanes.map((l)=>l.laneId).join(", ")}. Run lane execution before review.`)}}let phaseEvidence=await readPhaseEvidence(directory,phase),filesChangedSet=new Set;for(let lane of lanes)for(let file3 of lane.files)filesChangedSet.add(file3);let completedLanes=lanes.filter((l)=>l.status==="completed").length,failedLanes=lanes.filter((l)=>l.status==="failed").length,laneSummaries=lanes.map((lane)=>({laneId:lane.laneId,taskIds:lane.taskIds,files:lane.files,status:lane.status,agent:lane.agent})),degradedTasks=phaseEvidence?.degradedTasks??[],pendingDegraded=degradedTasks.filter((dt)=>!lanes.some((l)=>l.taskIds.includes(dt.taskId)&&l.status==="completed")).length,buildStatus="unknown";if(phaseEvidence?.status==="completed")buildStatus=failedLanes===0?"passed":"failed";else if(phaseEvidence?.status==="failed")buildStatus="failed";let pkg={phase,sessionID,laneSummaries,filesChanged:[...filesChangedSet],testResults:{totalLanes:lanes.length,completedLanes,failedLanes},buildStatus,degradationSummary:{totalDegraded:degradedTasks.length,resolvedDegraded:degradedTasks.length-pendingDegraded,pendingDegraded}};if(phaseEvidence?.validationArtifacts)pkg.validationArtifacts=phaseEvidence.validationArtifacts;if(requireDiffSummary){if(!phaseEvidence?.integratedDiffSummary)throw Error(`Integrated diff summary is required for phase ${phaseEvidence?.phase??"unknown"} but missing. Run the review step with diff evidence generation enabled.`);pkg.integratedDiffSummary=phaseEvidence.integratedDiffSummary}return pkg}function parseReviewerVerdict(responseText){let verdictMatch=responseText.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED)/);if(!verdictMatch)return null;let verdict=verdictMatch[1],lines=responseText.split(`
6339
6339
  `),verdictIndex=lines.findIndex((l)=>l.toUpperCase().match(/VERDICT\s*:\s*(APPROVED|NEEDS_REVISION|REJECTED)/i)),reason;if(verdictIndex>=0&&verdictIndex+1<lines.length){let reasonMatch=lines[verdictIndex+1].match(/^REASON\s*:\s*(.+)/i);if(reasonMatch)reason=reasonMatch[1].trim()}return{verdict,reason}}async function writeReviewerEvidence(directory,phase,verdict,reason){let evidenceDir=path243.join(directory,".swarm","evidence",String(phase));await fs137.mkdir(evidenceDir,{recursive:!0});let evidencePath=path243.join(evidenceDir,"lean-turbo-reviewer.json"),content=JSON.stringify({phase,verdict,reason:reason??null,timestamp:new Date().toISOString()},null,2),tempPath=`${evidencePath}.tmp.${process.pid}.${Date.now()}`;try{await fs137.writeFile(tempPath,content,"utf-8"),await fs137.rename(tempPath,evidencePath),invalidateCachedArtifact(evidencePath)}catch(error93){try{await fs137.unlink(tempPath)}catch{}throw error93}return evidencePath}async function defaultDispatchReviewerAgent(directory,reviewPackage,agentName,timeoutMs,parentSessionId,model,dispatcher){let activeDispatcher=dispatcher;if(!activeDispatcher){let legacyClient=swarmState.opencodeClient;if(!legacyClient)throw Error("ReviewModelDispatcher not available");activeDispatcher=createReviewModelDispatcher(legacyClient)}let system=`You are a read-only phase reviewer for Lean Turbo execution.
6340
6340
  Review the supplied phase execution evidence and decide whether the phase is ready to advance.
6341
6341
  Evaluate lane completion, unresolved degraded tasks, the file change set, and build status.
@@ -6696,5 +6696,5 @@ ${tailContent.join(`
6696
6696
  `)}
6697
6697
  ${footerLines.join(`
6698
6698
  `)}`}init_skill_propagation_gate();init_utils2();init_warning_buffer();init_cache_paths();import*as fs196 from"node:fs";import*as os26 from"node:os";import*as path316 from"node:path";import*as fs194 from"node:fs";import*as path314 from"node:path";var _internals235={realpathSyncNative:fs194.realpathSync.native};function hostWindowsPath(input){return input.replace(/^\/([a-zA-Z]):(?:[\\/]|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/cygdrive\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`).replace(/^\/mnt\/([a-zA-Z])(?:\/|$)/,(_m,d)=>`${d.toUpperCase()}:/`)}function hostNormalizePath(input){let resolved=path314.resolve(hostWindowsPath(input));try{return _internals235.realpathSyncNative(resolved)}catch{return resolved}}function hostNormalizePathPattern(pattern){if(pattern==="*")return pattern;let match=/^(.*)[\\/]\*$/.exec(pattern);if(!match)return hostNormalizePath(pattern);let dir=/^[A-Za-z]:$/.test(match[1])?`${match[1]}\\`:match[1];return path314.join(hostNormalizePath(dir),"*")}init_warning_buffer();init_swarm_branch();import*as fs195 from"node:fs";import*as path315 from"node:path";var MAX_CACHED_DIRECTORIES2=256,laneContextCache=new Map,_internals236={readFileSync:fs195.readFileSync,statSync:fs195.statSync,addDeferredWarning,clearCache:()=>{laneContextCache.clear()}},MAX_ANCESTOR_WALK_DEPTH=40,MAX_DETECTION_ATTEMPTS=3,DETECTION_RETRY_BACKOFF_MS=5;function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{}}function remember(key,value,io){if(!io.failed)return cache4(key,value);try{_internals236.addDeferredWarning(`[swarm] Could not read git metadata for ${key} after ${MAX_DETECTION_ATTEMPTS} attempts; worktree-lane permission scoping was skipped for it. If this directory IS a swarm lane, external-directory prompts raised there cannot be answered and the lane may hang. Check filesystem permissions and open-file limits, then restart the session.`)}catch{}return null}function cache4(key,value){if(laneContextCache.size>=MAX_CACHED_DIRECTORIES2){let oldest=laneContextCache.keys().next();if(!oldest.done)laneContextCache.delete(oldest.value)}return laneContextCache.set(key,value),value}function isSwarmOwnedBranch(gitDir,io){let head2;try{head2=_internals236.readFileSync(path315.join(gitDir,"HEAD"),"utf-8")}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return!1}let branch=/^\s*ref:\s*refs\/heads\/(.+?)\s*$/m.exec(head2)?.[1];if(!branch)return!1;return matchSwarmLaneBranch(branch)!==void 0}function readLinkedWorktreeGitDir(directory,io){let dotGit=path315.join(directory,".git"),stat21;try{stat21=_internals236.statSync(dotGit)}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return}if(!stat21.isFile())return;let contents;try{contents=_internals236.readFileSync(dotGit,"utf-8")}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0;return}let pointer=/^\s*gitdir:\s*(.+?)\s*$/m.exec(contents)?.[1];if(!pointer)return;return path315.resolve(directory,pointer)}function resolveMainWorktree(gitDir,io){let commonDir;try{let trimmed=_internals236.readFileSync(path315.join(gitDir,"commondir"),"utf-8").trim();if(trimmed)commonDir=path315.resolve(gitDir,trimmed)}catch(err2){if(err2?.code!=="ENOENT")io.failed=!0}if(commonDir){let parent2=path315.dirname(commonDir);return parent2&&parent2!==commonDir?parent2:void 0}let worktreesDir=path315.dirname(gitDir);if(path315.basename(worktreesDir)!=="worktrees")return;let sharedGitDir=path315.dirname(worktreesDir);if(path315.basename(sharedGitDir)!==".git")return;let parent=path315.dirname(sharedGitDir);return parent&&parent!==sharedGitDir?parent:void 0}function resolveLaneContext(directory){if(typeof directory!=="string"||directory.trim()==="")return null;let resolved;try{resolved=path315.resolve(directory)}catch{return null}let cached3=laneContextCache.get(resolved);if(cached3!==void 0)return cached3;let io={failed:!1},result=null;for(let attempt=1;attempt<=MAX_DETECTION_ATTEMPTS;attempt+=1){if(io={failed:!1},result=attemptDetection(resolved,io),result!==null||!io.failed)break;if(attempt<MAX_DETECTION_ATTEMPTS)sleepSync(DETECTION_RETRY_BACKOFF_MS)}if(result!==null)return cache4(resolved,result);return remember(resolved,null,io)}function attemptDetection(resolved,io){try{let laneRoot,gitDir,current=resolved;for(let depth=0;depth<MAX_ANCESTOR_WALK_DEPTH;depth+=1){let candidate2=readLinkedWorktreeGitDir(current,io);if(candidate2){laneRoot=current,gitDir=candidate2;break}let parent=path315.dirname(current);if(parent===current)break;current=parent}if(!laneRoot||!gitDir)return null;if(!(isSwarmOwnedBranch(gitDir,io)||matchSwarmLanePath(laneRoot)!==void 0))return null;let parentProjectPath=resolveMainWorktree(gitDir,io);if(!parentProjectPath)return null;if(path315.resolve(parentProjectPath)===laneRoot)return null;return{lanePath:laneRoot,parentProjectPath:path315.resolve(parentProjectPath)}}catch{return io.failed=!0,null}}class LastWinsRuleMap{entries=new Map;set(pattern,action){this.entries.delete(pattern),this.entries.set(pattern,action)}toObject(){return Object.fromEntries(this.entries)}}var SKILL_DIR_NAMES=["skill","skills"],HOST_HOME_SKILL_MARKERS=[".claude",".agents"];function laneDirectoryPattern(dir){return hostNormalizePathPattern(path316.join(dir,"*"))}function isExpressibleDirectory(dir){return!dir.includes("*")&&!dir.includes("?")}function push(out,seen,dir,reason){if(!dir)return;let resolved;try{resolved=path316.resolve(dir)}catch{return}if(!isExpressibleDirectory(resolved))return;let key=process.platform==="win32"?resolved.toLowerCase():resolved;if(seen.has(key))return;seen.add(key),out.push({dir:resolved,pattern:laneDirectoryPattern(resolved),reason})}function buildLaneAllowlist(lane,configuredSkillPaths=[],configuredSkillUrls=[]){let out=[],seen=new Set;push(out,seen,lane.parentProjectPath,"parent project the lane is a git worktree of"),push(out,seen,lane.lanePath,"the lane worktree itself"),push(out,seen,getPluginConfigDir(),"OpenCode XDG config dir (host Global.Path.config)"),push(out,seen,getHostConfigDir(),"OpenCode config dir override (OPENCODE_CONFIG_DIR), when set");let tmpRoot=os26.tmpdir();if(push(out,seen,path316.join(tmpRoot,"opencode"),"OpenCode's own temp dir (host Global.Path.tmp)"),process.platform==="win32")push(out,seen,path316.join(tmpRoot,"swwt"),"shortened-worktree lane root (Windows path-budget fallback)");push(out,seen,path316.join(getHostDataDir(),"plans"),"OpenCode plan storage (host `plan` agent's native allow)");let home;try{home=os26.homedir()}catch{home=void 0}let projectRoots=[{base:lane.parentProjectPath,label:"parent project"},{base:lane.lanePath,label:"lane"}];for(let marker of HOST_HOME_SKILL_MARKERS){for(let{base,label}of projectRoots)push(out,seen,path316.resolve(base,marker,"skills"),`skill root (${label}): ${marker}/skills`);if(home)push(out,seen,path316.resolve(home,marker,"skills"),`skill root (user level): ~/${marker}/skills`)}let configSkillRoots=[{base:getPluginConfigDir(),label:"XDG config dir"},{base:getHostConfigDir(),label:"config dir override"},...projectRoots.map(({base,label})=>({base:path316.resolve(base,".opencode"),label:`${label} .opencode`})),...home?[{base:path316.join(home,".opencode"),label:"user-level .opencode"}]:[]];for(let{base,label}of configSkillRoots)for(let dirName of SKILL_DIR_NAMES)push(out,seen,path316.resolve(base,dirName),`skill root (${label}): ${dirName}/`);for(let relative73 of SKILL_SEARCH_ROOTS){for(let{base,label}of projectRoots)push(out,seen,path316.resolve(base,relative73),`skill root (${label}): ${relative73}`);if(home)push(out,seen,path316.resolve(home,relative73),`skill root (user level): ~/${relative73}`)}if((Array.isArray(configuredSkillUrls)?configuredSkillUrls:[]).some((u)=>typeof u==="string"&&u.trim()!==""))push(out,seen,getHostSkillCacheDir(),"URL-sourced skill cache (only because skills.urls is configured)");let skillPaths=Array.isArray(configuredSkillPaths)?configuredSkillPaths:[];for(let configured of skillPaths){if(typeof configured!=="string"||configured.trim()==="")continue;let expanded=configured.startsWith("~/")&&home?path316.join(home,configured.slice(2)):configured;push(out,seen,path316.isAbsolute(expanded)?expanded:path316.resolve(lane.lanePath,expanded),`configured skills.path: ${configured}`)}return out}function normalizeExisting(existing){if(typeof existing==="string")return{"*":existing};if(existing&&typeof existing==="object"&&!Array.isArray(existing))return{...existing};return}function buildLaneExternalDirectoryRules(mode,lane,existing,precomputedAllowlist){if(mode==="off")return null;let rules=new LastWinsRuleMap;if(rules.set("*","deny"),mode==="scoped_allow")for(let entry of precomputedAllowlist??buildLaneAllowlist(lane))rules.set(entry.pattern,"allow");let coercedAskPatterns=[],user=normalizeExisting(existing);if(user)for(let[pattern,action]of Object.entries(user)){if(action==="ask"){coercedAskPatterns.push(pattern),rules.set(pattern,"deny");continue}rules.set(pattern,action)}return{rules:rules.toObject(),coercedAskPatterns}}function renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns=[]){let scope=mode==="deny"?"ALL external directory access is denied in this lane":`external directory access is limited to ${allowlist.length} justified path(s)`,parts=[`[swarm] Worktree-lane permissions active for ${lane.lanePath} (worktree of ${lane.parentProjectPath}).`,`Policy worktree.lane_permissions="${mode}": ${scope}; anything else is denied rather than left pending.`,'A lane instance has no TUI attached, so an "ask" there can never be answered and would hang the lane forever.'];if(coercedAskPatterns.length>0)parts.push(`Your configured external_directory "ask" rule(s) [${coercedAskPatterns.join(", ")}] were treated as "deny" here for that reason — change them to "allow" if the lane needs those paths.`);return parts.push("To widen the allowlist, add the directory to opencode.json:",' { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } }','To restore the previous (hanging) behaviour, set worktree.lane_permissions to "off".'),parts.join(" ")}var _internals237={resolveLaneContext,addDeferredWarning,appendFileSync:fs196.appendFileSync,mkdirSync:fs196.mkdirSync};function readConfiguredSkillList(opencodeConfig,key){let skills=opencodeConfig.skills;if(!skills||typeof skills!=="object"||Array.isArray(skills))return[];let value=skills[key];if(!Array.isArray(value))return[];return value.filter((v)=>typeof v==="string"&&v.trim()!=="")}function downgradeAgentAskRules(opencodeConfig){let coerced=[],agents=opencodeConfig.agent;if(!agents||typeof agents!=="object"||Array.isArray(agents))return coerced;for(let[agentName,rawAgent]of Object.entries(agents)){if(!rawAgent||typeof rawAgent!=="object"||Array.isArray(rawAgent))continue;let rawPermission=rawAgent.permission;if(!rawPermission||typeof rawPermission!=="object"||Array.isArray(rawPermission))continue;let agentPermission=rawPermission,external3=agentPermission.external_directory;if(external3==="ask"){agentPermission.external_directory="deny",coerced.push(`${agentName}.*`);continue}if(!external3||typeof external3!=="object"||Array.isArray(external3))continue;let map3=external3;for(let[pattern,action]of Object.entries(map3)){if(action!=="ask")continue;map3[pattern]="deny",coerced.push(`${agentName}.${pattern}`)}}return coerced}function recordLanePermissionEvent(directory,event){try{let eventsPath=validateSwarmPath(directory,"events.jsonl");_internals237.mkdirSync(path316.dirname(eventsPath),{recursive:!0}),_internals237.appendFileSync(eventsPath,`${JSON.stringify(event)}
6699
- `,"utf-8")}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals237.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals237.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500;function capSessionMap(map3,max){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path318.resolve(path318.dirname(fileURLToPath7(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,LOAD_PLUGIN_CONFIG_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(`
6700
- `)),output.system=system}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;let timer=setTimeout(()=>{for(let task2 of tasks)try{Promise.resolve(task2()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig;function overrideIndexInternalsForTest(overrides){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit;if(overrides.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides.createRepoGraphBuilderHook;if(overrides.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides.schedulePostResolutionTasks;if(overrides.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides.loadPluginConfigWithMetaAsync;if(overrides.loadSnapshot)loadSnapshotForInit=overrides.loadSnapshot;if(overrides.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides.ensureSwarmGitExcluded;if(overrides.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides.resolveAutoReviewConfig;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var OpenCodeSwarm=async(ctx)=>{let postResolutionTasks=[];try{let hooks=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),hooks}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map;function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")rememberAssistantUsage(part.sessionID,part)}}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(parentSessionID,taskOutput){let sessionIDs=[parentSessionID,...collectSessionIDs(taskOutput)];for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate2=value[key];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){clearDeferredWarnings();let __initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(ctx.directory),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=withTimeout(loadSnapshotForInit(ctx.directory),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}),gitExcludeP=withTimeout(ensureSwarmGitExcludedForInit(ctx.directory),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})});await Promise.all([configLoadP,snapshotP,gitExcludeP]);let{config:config3,loadedFromFile}=await configLoadP;if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:ctx.directory,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),initTelemetry(ctx.directory),startHeartbeatTracking();let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled?repoGraphHookFactory(ctx.directory,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(()=>{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),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),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,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path318.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID)await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID)delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-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-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs)}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(!failClosedRegionCompleted&&(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task"))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,agentName=(typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0)||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(telemetry.delegationEnd(sessionId,agentName,taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":safeHook(async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input.agent??"none"} session=${input.sessionID}`);if(await delegationHandler(input,output),input?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input.sessionID)}catch{}try{if(input?.sessionID&&input?.agent){if(stripKnownSwarmPrefix(String(input.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input.sessionID,"architectTurns",config3,{activeAgent:String(input.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input.agent??"none"}`)}),automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot};
6699
+ `,"utf-8")}catch{}}function applyLanePermissions(opencodeConfig,directory,mode){let lane=_internals237.resolveLaneContext(directory);if(!lane)return{lane:!1};let eventRoot=lane.lanePath;if(mode==="off")return recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"skipped",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,reason:'worktree.lane_permissions is "off"; external_directory asks in this lane cannot be answered and will hang'}),{lane:!0,mode};let permission=(()=>{let current=opencodeConfig.permission;if(current&&typeof current==="object"&&!Array.isArray(current))return current;let created={};return opencodeConfig.permission=created,created})(),agentCoerced=downgradeAgentAskRules(opencodeConfig),allowlist=mode==="scoped_allow"?buildLaneAllowlist(lane,readConfiguredSkillList(opencodeConfig,"paths"),readConfiguredSkillList(opencodeConfig,"urls")):[],build=buildLaneExternalDirectoryRules(mode,lane,permission.external_directory,allowlist);if(!build)return{lane:!0,mode};let{rules,coercedAskPatterns:topLevelCoerced}=build;permission.external_directory=rules;let coercedAskPatterns=[...topLevelCoerced,...agentCoerced];return _internals237.addDeferredWarning(renderLanePermissionAdvisory(mode,lane,allowlist,coercedAskPatterns)),recordLanePermissionEvent(eventRoot,{event:"lane_permissions",timestamp:new Date().toISOString(),decision:"applied",mode,lanePath:lane.lanePath,parentProjectPath:lane.parentProjectPath,allowlist:allowlist.map((entry)=>({pattern:entry.pattern,reason:entry.reason})),rules,coercedAskPatterns,remedy:'Add { "permission": { "external_directory": { "<absolute-dir>/*": "allow" } } } to opencode.json to widen the allowlist.'}),{lane:!0,mode,rules}}init_warning_buffer();init_archive_sqlite();init_fixtures();init_gate_ground_truth();init_pr_review_recovery();init_public_api();var _heartbeatTimers=new Map,MAX_TRACKED_HEARTBEAT_SESSIONS=500;function capSessionMap(map3,max){while(map3.size>max){let oldest=map3.keys().next().value;if(oldest===void 0)break;map3.delete(oldest)}}var _delegationTelemetryByCallID=new Map,MAX_TRACKED_DELEGATION_TELEMETRY=500;function _resetDelegationTelemetryPairingForTesting(){_delegationTelemetryByCallID.clear()}var SWARM_COMMAND_SYSTEM_RULE_TAG="[opencode-swarm:swarm-command-rule]",PACKAGE_ROOT2=path318.resolve(path318.dirname(fileURLToPath7(import.meta.url)),".."),SYNC_BUNDLED_SKILLS_TIMEOUT_MS=2000,LOAD_PLUGIN_CONFIG_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(`
6700
+ `)),output.system=system}}function schedulePostResolutionTasks(tasks){if(tasks.length===0)return;let timer=setTimeout(()=>{for(let task2 of tasks)try{Promise.resolve(task2()).catch((err2)=>{log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})}catch(err2){log("post-resolution startup task failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}},0);if(typeof timer.unref==="function")timer.unref()}var createRepoGraphBuilderHookForInit=createRepoGraphBuilderHook,schedulePostResolutionTasksForInit=schedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=loadPluginConfigWithMetaAsync,loadSnapshotForInit=loadSnapshot,ensureSwarmGitExcludedForInit=ensureSwarmGitExcluded,resolveAutoReviewConfigForInit=resolveAutoReviewConfig;function overrideIndexInternalsForTest(overrides){let previousCreateRepoGraphBuilderHook=createRepoGraphBuilderHookForInit,previousSchedulePostResolutionTasks=schedulePostResolutionTasksForInit,previousLoadPluginConfigWithMetaAsync=loadPluginConfigWithMetaAsyncForInit,previousLoadSnapshot=loadSnapshotForInit,previousEnsureSwarmGitExcluded=ensureSwarmGitExcludedForInit,previousResolveAutoReviewConfig=resolveAutoReviewConfigForInit;if(overrides.createRepoGraphBuilderHook)createRepoGraphBuilderHookForInit=overrides.createRepoGraphBuilderHook;if(overrides.schedulePostResolutionTasks)schedulePostResolutionTasksForInit=overrides.schedulePostResolutionTasks;if(overrides.loadPluginConfigWithMetaAsync)loadPluginConfigWithMetaAsyncForInit=overrides.loadPluginConfigWithMetaAsync;if(overrides.loadSnapshot)loadSnapshotForInit=overrides.loadSnapshot;if(overrides.ensureSwarmGitExcluded)ensureSwarmGitExcludedForInit=overrides.ensureSwarmGitExcluded;if(overrides.resolveAutoReviewConfig)resolveAutoReviewConfigForInit=overrides.resolveAutoReviewConfig;return()=>{createRepoGraphBuilderHookForInit=previousCreateRepoGraphBuilderHook,schedulePostResolutionTasksForInit=previousSchedulePostResolutionTasks,loadPluginConfigWithMetaAsyncForInit=previousLoadPluginConfigWithMetaAsync,loadSnapshotForInit=previousLoadSnapshot,ensureSwarmGitExcludedForInit=previousEnsureSwarmGitExcluded,resolveAutoReviewConfigForInit=previousResolveAutoReviewConfig}}function schedulePostResolutionTasksForTest(tasks){schedulePostResolutionTasks(tasks)}function computeEffectiveTruncatableTools(defaultTools,configuredTools){let effective=configuredTools&&configuredTools.length>0?new Set(configuredTools):new Set(defaultTools);for(let exempt of SUMMARIZER_EXEMPT_TOOL_NAMES)effective.delete(exempt);return effective}var OpenCodeSwarm=async(ctx)=>{let postResolutionTasks=[];try{let hooks=await initializeOpenCodeSwarm(ctx,postResolutionTasks);return schedulePostResolutionTasksForInit(postResolutionTasks),hooks}catch(err2){let stack=err2 instanceof Error?err2.stack??err2.message:String(err2);throw console.error("[opencode-swarm] FATAL: plugin initialization failed. Plugin will not be available."),console.error(stack),err2}},MAX_TRACKED_ASSISTANT_USAGE_EVENTS=200,latestAssistantUsageBySession=new Map;function rememberAssistantUsageEvent(input){let event=isPlainRecord3(input)?input.event:void 0;if(!isPlainRecord3(event))return;if(event.type==="message.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,info=isPlainRecord3(properties?.info)?properties.info:void 0;if(info?.role==="assistant")rememberAssistantUsage(info.sessionID,info);return}if(event.type==="message.part.updated"){let properties=isPlainRecord3(event.properties)?event.properties:void 0,part=isPlainRecord3(properties?.part)?properties.part:void 0;if(part?.type==="step-finish")rememberAssistantUsage(part.sessionID,part)}}function rememberAssistantUsage(sessionID,raw){if(typeof sessionID!=="string"||sessionID.trim()==="")return;latestAssistantUsageBySession.set(sessionID,raw);while(latestAssistantUsageBySession.size>MAX_TRACKED_ASSISTANT_USAGE_EVENTS){let oldest=latestAssistantUsageBySession.keys().next().value;if(oldest===void 0)break;latestAssistantUsageBySession.delete(oldest)}}function consumeAssistantUsageForTask(parentSessionID,taskOutput){let sessionIDs=[parentSessionID,...collectSessionIDs(taskOutput)];for(let sessionID of sessionIDs){let usage=latestAssistantUsageBySession.get(sessionID);if(usage!==void 0)return latestAssistantUsageBySession.delete(sessionID),usage}return}function collectSessionIDs(raw){let found=[],seen=new Set,visit=(value,depth)=>{if(depth>3||!isPlainRecord3(value)||seen.has(value))return;seen.add(value);for(let key of["sessionID","sessionId","session_id"]){let candidate2=value[key];if(typeof candidate2==="string"&&candidate2.trim()!=="")found.push(candidate2)}for(let key of["metadata","data","info","message","response","output"])visit(value[key],depth+1)};return visit(raw,0),[...new Set(found)]}function isPlainRecord3(value){return typeof value==="object"&&value!==null&&!Array.isArray(value)}async function initializeOpenCodeSwarm(ctx,postResolutionTasks){clearDeferredWarnings();let __initIoStart=performance2.now(),configLoadP=withTimeout(loadPluginConfigWithMetaAsyncForInit(ctx.directory),LOAD_PLUGIN_CONFIG_TIMEOUT_MS,Error(`loadPluginConfigWithMetaAsync exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; continuing with safe-default config`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("loadPluginConfig timed out or failed (non-fatal)",{error:msg}),advisoryWarn(`[opencode-swarm] Config load exceeded ${LOAD_PLUGIN_CONFIG_TIMEOUT_MS}ms budget; running with default configuration for this session.`),getSafeDefaultConfigLoadResult()}),snapshotP=withTimeout(loadSnapshotForInit(ctx.directory),5000,Error("loadSnapshot exceeded 5s budget; continuing without snapshot rehydration")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("loadSnapshot timed out or failed (non-fatal)",{error:msg})}),gitExcludeP=withTimeout(ensureSwarmGitExcludedForInit(ctx.directory),ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS,Error(`ensureSwarmGitExcluded exceeded ${ENSURE_SWARM_GIT_EXCLUDED_OUTER_TIMEOUT_MS}ms budget; continuing without git-hygiene check`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("ensureSwarmGitExcluded timed out or failed (non-fatal)",{error:msg})});await Promise.all([configLoadP,snapshotP,gitExcludeP]);let{config:config3,loadedFromFile}=await configLoadP;if(log(`init-path I/O completed in ${(performance2.now()-__initIoStart).toFixed(1)}ms (parallel: config+snapshot+git-exclude)`),config3.full_auto?.enabled===!0){let criticModel=config3.full_auto.critic_model??config3.agents?.critic?.model??DEFAULT_MODELS.critic,architectModel=config3.agents?.architect?.model??DEFAULT_MODELS.default;if(criticModel===architectModel)if(!config3.quiet)console.warn("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)");else addDeferredWarning("[opencode-swarm] Full-auto mode warning: critic model matches architect model. Model validation is advisory-only; full-auto remains enabled. (Runtime architect model is determined by the orchestrator)")}{let noFallback=[],hasNoFallback=(cfg)=>cfg.model&&(!cfg.fallback_models||cfg.fallback_models.length===0);if(config3.agents){for(let[name,cfg]of Object.entries(config3.agents))if(hasNoFallback(cfg))noFallback.push(`${name}(${cfg.model})`)}if(config3.swarms){for(let[swarmId,swarm]of Object.entries(config3.swarms))if(swarm.agents){for(let[name,cfg]of Object.entries(swarm.agents))if(hasNoFallback(cfg))noFallback.push(`${swarmId}/${name}(${cfg.model})`)}}if(noFallback.length>0){let msg=`[opencode-swarm] WARNING: ${noFallback.length} agent(s) use a custom model without fallback_models: `+noFallback.join(", ")+'. Add "fallback_models": ["model-a"] to each agent config for reliability.';if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}swarmState.fullAutoEnabledInConfig=config3.full_auto?.enabled===!0,swarmState.opencodeClient=ctx.client,initObservability({directory:ctx.directory,provenance:{pluginVersion:package_default.version,runtime:process.versions.bun===void 0?"node":"bun",runtimeVersion:process.versions.bun??process.versions.node,os:process.platform,arch:process.arch}}),initTelemetry(ctx.directory),startHeartbeatTracking();let repoGraphConfig=RepoGraphConfigSchema.parse(config3.repo_graph??{}),repoGraphHookFactory=createRepoGraphBuilderHookForInit,repoGraphHook=repoGraphConfig.enabled?repoGraphHookFactory(ctx.directory,void 0,{enabled:!0,initRefresh:repoGraphConfig.init_refresh,refreshCap:repoGraphConfig.refresh_cap,walkBudgetMs:repoGraphConfig.walk_budget_ms,maxFiles:repoGraphConfig.max_files,excludeDirs:repoGraphConfig.exclude_dirs}):null;if(repoGraphHook)postResolutionTasks.push(()=>{let watchdog=setTimeout(()=>{log("[repo-graph] init exceeded 30s budget; scan will continue but is overdue")},30000);if(typeof watchdog.unref==="function")watchdog.unref();repoGraphHook.init().catch(()=>{}).finally(()=>clearTimeout(watchdog))});if(postResolutionTasks.push(()=>{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),postResolutionTasks.push(()=>{withTimeout(syncBundledProjectSkillsIfMissingAsync(ctx.directory,PACKAGE_ROOT2,config3.quiet),SYNC_BUNDLED_SKILLS_TIMEOUT_MS,Error(`syncBundledProjectSkillsIfMissingAsync exceeded ${SYNC_BUNDLED_SKILLS_TIMEOUT_MS}ms budget; continuing without skill materialization (command-path sync remains a backstop)`)).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("bundled skill materialization timed out or failed (non-fatal)",{error:msg})})}),config3.version_check!==!1)postResolutionTasks.push(()=>{scheduleVersionCheck(package_default.version,(msg)=>{if(config3.quiet)addDeferredWarning(msg);else console.warn(msg)})});let projectContext=await withTimeout((async()=>{return(await Promise.resolve().then(() => (init_project_context(),exports_project_context))).buildProjectContext(ctx.directory)})(),300,Error("language-backend detection exceeded 300ms; continuing with unresolved sentinels")).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);return log("language-backend detection timed out or failed (non-fatal)",{error:msg}),null}),autoReviewConfig;try{autoReviewConfig=resolveAutoReviewConfigForInit(config3.auto_review??{})}catch(error93){addDeferredWarning(`[swarm] Invalid auto_review configuration; auto-review is disabled until corrected: ${error93 instanceof Error?error93.message:String(error93)}`),autoReviewConfig=resolveAutoReviewConfigForInit({enabled:!1})}let configWithResolvedAutoReview={...config3,auto_review:autoReviewConfig},agents=getAgentConfigs(configWithResolvedAutoReview,ctx.directory,void 0,projectContext??void 0),agentDefinitions=createAgents(configWithResolvedAutoReview,projectContext??void 0),agentDefinitionMap=Object.fromEntries(agentDefinitions.map((agent)=>[agent.name,agent])),instanceGeneratedAgentNames=Object.freeze(Object.keys(agents));swarmState.curatorInitAgentNames=Object.keys(agents).filter((k)=>k==="curator_init"||k.endsWith("_curator_init")),swarmState.curatorPhaseAgentNames=Object.keys(agents).filter((k)=>k==="curator_phase"||k.endsWith("_curator_phase")),swarmState.curatorPostmortemAgentNames=Object.keys(agents).filter((k)=>k==="curator_postmortem"||k.endsWith("_curator_postmortem")),swarmState.curatorConsolidationAgentNames=Object.keys(agents).filter((k)=>k==="curator_consolidation"||k.endsWith("_curator_consolidation")),swarmState.skillImproverAgentNames=Object.keys(agents).filter((k)=>k==="skill_improver"||k.endsWith("_skill_improver")),swarmState.specWriterAgentNames=Object.keys(agents).filter((k)=>k==="spec_writer"||k.endsWith("_spec_writer")),swarmState.generatedAgentNames=[...instanceGeneratedAgentNames];let pipelineHook=createPipelineTrackerHook(config3,ctx.directory),systemEnhancerHook=createSystemEnhancerHook(config3,ctx.directory),contextCapsuleInjectHook=createContextCapsuleInjectHook(config3,ctx.directory),compactionHook=createCompactionCustomizerHook(config3,ctx.directory),resolveIncomingAgentModel=(agentName)=>resolveRuntimeAgentModel(config3,agents,agentName),contextBudgetHandler=createContextBudgetHandler(config3,resolveIncomingAgentModel),evaluationModelDispatcher=createEvaluationModelDispatcher(ctx.client),reviewModelDispatcher=createReviewModelDispatcher(ctx.client),findingValidationScheduler=createFindingValidationScheduler(),reviewAgentModelRegistry=captureReviewAgentModelRegistry(config3,instanceGeneratedAgentNames),getActiveReviewAgentName=(sessionID)=>swarmState.activeAgent.get(sessionID)??swarmState.agentSessions.get(sessionID)?.agentName,roleFilterSystemHook=createRoleFilterSystemHook(getActiveReviewAgentName),commandHandler=createSwarmCommandHandler(ctx.directory,agentDefinitionMap,{getActiveAgentName:getActiveReviewAgentName,packageRoot:PACKAGE_ROOT2,registeredAgents:agents,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,reviewAgentModelRegistry}),swarmCommandSystemRuleHook=createSwarmCommandSystemRuleHook(agentDefinitionMap,agents),activityHooks=createAgentActivityHooks(config3,ctx.directory),learningConfig=LearningConfigSchema.parse(config3.learning??{}),prmHook=createPrmHook(config3.prm??PrmConfigSchema.parse({}),ctx.directory,resolvePrmPatternPersistenceOptions(learningConfig)),trajectoryLoggerHook=createTrajectoryLoggerHook({enabled:!0,max_lines:1000},ctx.directory),delegationGateHooks=createDelegationGateHook(configWithResolvedAutoReview,ctx.directory),advisoryInjector=(sessionId,message)=>{let session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,message)},backgroundCompletionObserver=createBackgroundCompletionObserver({config:{enabled:config3.hooks?.background_subagents===!0},directory:ctx.directory,reviewerReceiptOptions:{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler}}),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,resolveIncomingAgentModel),durableBackgroundAdvisoryMessagesTransform=async(input,output)=>{let mctx=resolveMessageTransformContext(output);if(!mctx.sessionID){await guardrailsHooks.messagesTransform(input,output);return}let observedTexts=(output.messages??[]).flatMap((message)=>(message.parts??[]).filter((part)=>part.type==="text"&&typeof part.text==="string").map((part)=>part.text));await backgroundCompletionObserver.ackObservedAdvisories(mctx.sessionID,observedTexts);let prepared=await backgroundCompletionObserver.prepareAdvisories(mctx.sessionID);if(!prepared){await guardrailsHooks.messagesTransform(input,output);return}let session=swarmState.agentSessions.get(mctx.sessionID),pendingBefore=session?[...session.pendingAdvisoryMessages??[]]:void 0,guardrailsSnapshot=session?{resumeModelAdvisoryDone:session.resumeModelAdvisoryDone,configModelAdvisoryDone:session.configModelAdvisoryDone,lastObservedModel:session.lastObservedModel,lastObservedProviderID:session.lastObservedProviderID,lastProviderRecoveryFingerprint:session.lastProviderRecoveryFingerprint,loopWarningPending:session.loopWarningPending}:void 0,messagesBefore=output.messages?structuredClone(output.messages):void 0;try{if(session)for(let message of prepared.messages)pushAdvisory(session,message);if(await guardrailsHooks.messagesTransform(input,output),!prepared.messages.every((message)=>(output.messages??[]).some((candidate2)=>(candidate2.parts??[]).some((part)=>part.type==="text"&&typeof part.text==="string"&&part.text.includes(message)))))throw Error("durable background advisory insertion failed")}catch(error93){if(session&&pendingBefore)session.pendingAdvisoryMessages=pendingBefore;if(session&&guardrailsSnapshot)session.resumeModelAdvisoryDone=guardrailsSnapshot.resumeModelAdvisoryDone,session.configModelAdvisoryDone=guardrailsSnapshot.configModelAdvisoryDone,session.lastObservedModel=guardrailsSnapshot.lastObservedModel,session.lastObservedProviderID=guardrailsSnapshot.lastObservedProviderID,session.lastProviderRecoveryFingerprint=guardrailsSnapshot.lastProviderRecoveryFingerprint,session.loopWarningPending=guardrailsSnapshot.loopWarningPending;if(Array.isArray(output.messages)&&messagesBefore){output.messages.length=0;for(let message of messagesBefore)output.messages.push(message)}else output.messages=messagesBefore;await backgroundCompletionObserver.releaseAdvisories(mctx.sessionID,prepared),warn(`[background] advisory injection rolled back for ${mctx.sessionID}: ${error93 instanceof Error?error93.message:String(error93)}`)}},fullAutoInterceptHook=createFullAutoInterceptHook(config3,ctx.directory),fullAutoPermissionHook=createFullAutoPermissionHook({config:config3,directory:ctx.directory}),fullAutoInputProbeHook=createFullAutoInputProbeHook({config:config3,directory:ctx.directory}),fullAutoDelegationHook=createFullAutoDelegationHook({config:config3,directory:ctx.directory}),ccCommandInterceptHook=createCcCommandInterceptHook({}),issueTraceHook=createIssueTraceHook(config3,ctx.directory),watchdogConfig=WatchdogConfigSchema.parse(config3.watchdog??{}),scopeGuardHook=createScopeGuardHook({enabled:watchdogConfig.scope_guard,skip_in_turbo:watchdogConfig.skip_in_turbo},ctx.directory,advisoryInjector),prWorkflowResponseGate=createPrWorkflowResponseGate({directory:ctx.directory,client:ctx.client}),prWorkflowSessionResolver=createPrWorkflowSessionResolver({directory:ctx.directory,client:ctx.client}),delegationLedgerHook=createDelegationLedgerHook({enabled:watchdogConfig.delegation_ledger},ctx.directory,advisoryInjector),initOrphanRecoveryAdvisoryHook=createInitOrphanRecoveryAdvisoryHook(ctx.directory),selfReviewConfig=SelfReviewConfigSchema.parse(config3.self_review??{}),selfReviewHook=createSelfReviewHook({enabled:selfReviewConfig.enabled,skip_in_turbo:selfReviewConfig.skip_in_turbo},advisoryInjector),autoReviewHook=createAutoReviewHook({config:autoReviewConfig,directory:ctx.directory,dispatcher:reviewModelDispatcher,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,getActiveAgentName:getActiveReviewAgentName,injectAdvisory:advisoryInjector}),summaryConfig=SummaryConfigSchema.parse(config3.summaries??{}),toolSummarizerHook=createToolSummarizerHook(summaryConfig,ctx.directory),knowledgeConfigBase=config3.knowledge??{},knowledgeConfig=KnowledgeConfigSchema.parse(knowledgeConfigBase),skillImproverConfig=SkillImproverConfigSchema.parse(config3.skill_improver??{}),skillPropagationConfig=SkillPropagationConfigSchema.parse(config3.skillPropagation??{});if(skillImproverConfig.enabled&&skillImproverConfig.trigger==="scheduled")postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_skill_consolidation(),exports_skill_consolidation)).then(({runSkillConsolidationFireAndForget:runSkillConsolidationFireAndForget2})=>{runSkillConsolidationFireAndForget2({directory:ctx.directory,config:skillImproverConfig,source:"startup",enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},evaluateDrafts:!0},void 0,(err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("scheduled skill consolidation failed (non-fatal)",{error:msg})})}).catch((err2)=>{let msg=err2 instanceof Error?err2.message:String(err2);log("failed to schedule skill consolidation (non-fatal)",{error:msg})})});let knowledgeCuratorHook=knowledgeConfig.enabled?createKnowledgeCuratorHook(ctx.directory,knowledgeConfig,{llmDelegateFactory:(sessionID)=>createCuratorLLMDelegate(ctx.directory,"phase",sessionID),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}}):void 0,hivePromoterHook=knowledgeConfig.enabled&&knowledgeConfig.hive_enabled?createHivePromoterHook(ctx.directory,knowledgeConfig):void 0,knowledgeInjectorHook=knowledgeConfig.enabled?createKnowledgeInjectorHook(ctx.directory,knowledgeConfig,config3.context_budget?.model_limits??{},config3.context_budget?.unified_injection_tokens):void 0,steeringConsumedHook=createSteeringConsumedHook(ctx.directory),coChangeSuggesterHook=createCoChangeSuggesterHook(ctx.directory),darkMatterDetectorHook=createDarkMatterDetectorHook(ctx.directory),slopDetectorHook=config3.slop_detector?.enabled!==!1?createSlopDetectorHook(config3.slop_detector??{enabled:!0,classThreshold:3,commentStripThreshold:5,diffLineThreshold:200,importHygieneThreshold:2},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,incrementalVerifyHook=config3.incremental_verify?.enabled!==!1?createIncrementalVerifyHook(config3.incremental_verify??{enabled:!0,command:null,timeoutMs:30000,triggerAgents:["coder"]},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,compactionServiceHook=config3.compaction_service?.enabled!==!1?createCompactionService(config3.compaction_service??{enabled:!0,observationThreshold:40,reflectionThreshold:60,emergencyThreshold:80,preserveLastNTurns:5},ctx.directory,(sessionId,message)=>{let s=swarmState.agentSessions.get(sessionId);if(s)pushAdvisory(s,message)}):null,snapshotWriterHook=createSnapshotWriterHook(ctx.directory),automationConfig=AutomationConfigSchema.parse(config3.automation??{}),automationManager,preflightTriggerManager,statusArtifact,prMonitorWorker=null,planSyncWorker=null;if(automationConfig.mode!=="manual"){automationManager=createAutomationManager(automationConfig),automationManager.start();let{PreflightTriggerManager:PTM}=await Promise.resolve().then(() => (init_trigger(),exports_trigger));preflightTriggerManager=new PTM(automationConfig);let{AutomationStatusArtifact:ASA}=await Promise.resolve().then(() => (init_status_artifact(),exports_status_artifact)),swarmDir=path318.resolve(ctx.directory,".swarm");if(statusArtifact=new ASA(swarmDir),statusArtifact.updateConfig(automationConfig.mode,automationConfig.capabilities),automationConfig.capabilities?.evidence_auto_summaries===!0){let{createEvidenceSummaryIntegration:createEvidenceSummaryIntegration2}=await Promise.resolve().then(() => (init_evidence_summary_integration(),exports_evidence_summary_integration));createEvidenceSummaryIntegration2({automationConfig,directory:ctx.directory,projectDir:ctx.directory,summaryFilename:"evidence-summary.json"}),log("Evidence summary integration initialized",{directory:ctx.directory})}if(automationConfig.capabilities?.phase_preflight===!0){let{createPreflightIntegration:createPreflightIntegration2}=await Promise.resolve().then(() => (init_preflight_integration(),exports_preflight_integration));try{let{manager}=createPreflightIntegration2({automationConfig,directory:ctx.directory,swarmDir});preflightTriggerManager=manager,log("Preflight integration initialized",{directory:ctx.directory})}catch(err2){log("Preflight integration failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}if(automationConfig.capabilities?.plan_sync===!0)try{planSyncWorker=new PlanSyncWorker({directory:ctx.directory}),planSyncWorker.start(),log("PlanSyncWorker initialized",{directory:ctx.directory})}catch(err2){log("PlanSyncWorker failed to initialize (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}log("Automation framework initialized",{mode:automationConfig.mode,enabled:automationManager?.isEnabled(),running:automationManager?.isActive(),preflightEnabled:preflightTriggerManager?.isEnabled()})}let prMonitorConfig=PrMonitorConfigSchema.parse(config3.pr_monitor??{});function ensurePrMonitorWorkerRunning(directory){try{if(!prMonitorConfig.enabled)return;if(!prMonitorWorker)prMonitorWorker=new PrMonitorWorker({directory,config:prMonitorConfig});if(!prMonitorWorker.isRunning())prMonitorWorker.start(),log("PR Monitor Worker started",{directory})}catch(err2){error48("[pr-monitor] Worker failed to start (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}setOnSubscriptionCreated((directory,_record3)=>{ensurePrMonitorWorkerRunning(directory)});let prEventCleanup=null,prEventDelivery=null;if(prMonitorConfig.enabled){try{let{registerPrEventSubscribers:registerPrEventSubscribers2}=await Promise.resolve().then(() => (init_pr_event_subscribers(),exports_pr_event_subscribers));prEventCleanup=registerPrEventSubscribers2({directory:ctx.directory,config:prMonitorConfig})}catch(err2){log("[pr-monitor] Failed to register PR event subscribers (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}if(prMonitorConfig.event_delivery==="prompt")try{let deliveryModule=await Promise.resolve().then(() => (init_pr_event_delivery(),exports_pr_event_delivery));deliveryModule.registerPrEventDelivery({client:ctx.client,directory:ctx.directory,config:prMonitorConfig}),prEventDelivery={noteSessionIdle:deliveryModule.noteSessionIdle,unregisterPrEventDelivery:deliveryModule.unregisterPrEventDelivery}}catch(err2){log("[pr-monitor] Failed to register wake delivery (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})}}let prAutoSubscribeHook=createPrAutoSubscribeHook(ctx.directory,prMonitorConfig);if(prMonitorConfig.enabled)postResolutionTasks.push(()=>{listActive(ctx.directory).then((active)=>{if(active.length>0)ensurePrMonitorWorkerRunning(ctx.directory)}).catch((err2)=>{error48("[pr-monitor] Startup scan failed (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})});let cleanupAutomation=()=>{automationManager?.stop(),prMonitorWorker?.stop(),planSyncWorker?.stop(),prEventCleanup?.(),prEventDelivery?.unregisterPrEventDelivery()};if(process.on("exit",cleanupAutomation),shouldRunOnStartup(automationConfig)){let enableAutofix=automationConfig.capabilities?.config_doctor_autofix===!0;postResolutionTasks.push(()=>{return Promise.resolve().then(() => (init_config_doctor(),exports_config_doctor)).then(({runConfigDoctorWithFixes:runConfigDoctorWithFixes2})=>{return runConfigDoctorWithFixes2(ctx.directory,config3,enableAutofix).then((doctorResult)=>{if(doctorResult.result.findings.length>0){log("Config Doctor ran on startup",{findings:doctorResult.result.findings.length,errors:doctorResult.result.summary.error,warnings:doctorResult.result.summary.warn,appliedFixes:doctorResult.appliedFixes.length,autofixEnabled:enableAutofix});try{let autoFixableCount=doctorResult.result.findings.filter((f)=>f.autoFixable).length,appliedCount=doctorResult.appliedFixes.length;if(!enableAutofix&&autoFixableCount>0){let msg=`[opencode-swarm] Config Doctor found ${autoFixableCount} auto-fixable issue(s). Run /swarm config doctor --fix to apply.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}else if(enableAutofix){let parts=[];if(appliedCount>0)parts.push(`applied ${appliedCount} fix(es) automatically`);let unapplied=Math.max(0,autoFixableCount-appliedCount);if(unapplied>0)parts.push(`${unapplied} auto-fixable issue(s) need explicit review — run /swarm config doctor --fix`);if(parts.length>0){let msg=`[opencode-swarm] Config Doctor: ${parts.join("; ")}.`;if(!config3.quiet)console.warn(msg);else addDeferredWarning(msg)}}}catch{}}}).catch((err2)=>{log("Config Doctor error (non-fatal)",{error:err2 instanceof Error?err2.message:String(err2)})})})})}return log("Plugin initialized",{maxIterations:config3.max_iterations,agentCount:Object.keys(agents).length,hooks:{pipeline:!!pipelineHook["experimental.chat.messages.transform"],systemEnhancer:!!systemEnhancerHook["experimental.chat.system.transform"],compaction:!!compactionHook["experimental.session.compacting"],contextBudget:!!contextBudgetHandler,commands:!0,agentActivity:config3.hooks?.agent_activity!==!1,delegationTracker:config3.hooks?.delegation_tracker===!0,guardrails:guardrailsConfig.enabled,toolSummarizer:summaryConfig.enabled,knowledge:knowledgeConfig.enabled},automation:{mode:automationConfig.mode,capabilities:automationConfig.capabilities}}),{name:"opencode-swarm",agent:agents,tool:buildPluginToolObject(agentDefinitionMap,config3,evaluationModelDispatcher,reviewModelDispatcher,instanceGeneratedAgentNames,reviewAgentModelRegistry,getActiveReviewAgentName),event:async(input)=>{try{rememberAssistantUsageEvent(input);let lifecycleEvent=input.event;if(lifecycleEvent?.type==="message.part.updated"){let part=lifecycleEvent.properties?.part,metadata=part?.state?.metadata,partTool=typeof part?.tool==="string"?normalizeToolName(part.tool)?.toLowerCase():void 0,eventParentSessionID=typeof part?.sessionID==="string"&&part.sessionID.trim()!==""?part.sessionID:void 0,eventChildSessionID=typeof metadata?.sessionId==="string"&&metadata.sessionId.trim()!==""?metadata.sessionId:void 0;if(part?.type==="tool"&&partTool==="task"&&typeof part.callID==="string"&&part.callID.trim()!==""&&eventParentSessionID!==void 0&&eventChildSessionID!==void 0&&eventParentSessionID!==eventChildSessionID)await delegationGateHooks.taskMetadata({callID:part.callID,parentSessionID:eventParentSessionID,childSessionID:eventChildSessionID})}let lifecycleStatus=lifecycleEvent?.properties?.status;if(lifecycleEvent?.type==="session.deleted"||lifecycleEvent?.type==="session.removed"||lifecycleEvent?.type==="session.idle"||lifecycleEvent?.type==="session.error"||lifecycleEvent?.type==="session.status"&&(lifecycleStatus==="idle"||typeof lifecycleStatus==="object"&&(lifecycleStatus.type==="idle"||lifecycleStatus.type==="error"))){let properties=lifecycleEvent.properties,sessionID=properties?.sessionID??properties?.sessionId??properties?.info?.sessionID??properties?.info?.id??properties?.id;if(sessionID)delegationGateHooks.sessionEnded(sessionID,lifecycleEvent.type==="session.deleted"||lifecycleEvent.type==="session.removed")}if(prWorkflowSessionResolver.observeEvent(input),await prWorkflowResponseGate.event(input),prEventDelivery){let evt=input.event,idleSessionID=evt?.properties?.sessionID??evt?.data?.sessionID;if(evt?.type==="session.idle"&&typeof idleSessionID==="string")prEventDelivery.noteSessionIdle(idleSessionID)}await backgroundCompletionObserver.event(input)}catch(err2){warn(`[swarm] event hook error: ${err2 instanceof Error?err2.message:String(err2)}`)}},config:async(opencodeConfig)=>{let isObjectRecord=(value)=>typeof value==="object"&&value!==null,pluginConfig=opencodeConfig;if(!isObjectRecord(pluginConfig.agent))pluginConfig.agent={};let agentConfig=pluginConfig.agent;Object.assign(agentConfig,agents);try{applyLanePermissions(opencodeConfig,ctx.directory,config3?.worktree?.lane_permissions??"scoped_allow")}catch(err2){addDeferredWarning(`[swarm] lane permission scoping failed: ${err2 instanceof Error?err2.message:String(err2)}`)}let autoSelect=config3?.auto_select_architect;if(autoSelect)if(Object.keys(agents).some((name)=>stripKnownSwarmPrefix(name)==="architect")){for(let builtin of["build","plan"]){let existing=agentConfig[builtin];if(isObjectRecord(existing)&&existing.disable===!0)continue;agentConfig[builtin]={...isObjectRecord(existing)?existing:{},disable:!0}}if(autoSelect===!0){let primaryArchitects=Object.entries(agents).filter(([name,cfg])=>stripKnownSwarmPrefix(name)==="architect"&&isObjectRecord(cfg)&&cfg.mode==="primary");if(primaryArchitects.length>1){let names=primaryArchitects.map(([n])=>n).join(", ");addDeferredWarning(`[swarm] auto_select_architect is true but ${primaryArchitects.length} architect agents are primary (${names}). Consider setting auto_select_architect to a specific agent name.`)}}if(typeof autoSelect==="string"&&autoSelect!==""){let targetName=autoSelect;if(Object.hasOwn(agents,targetName)&&stripKnownSwarmPrefix(targetName)==="architect"){for(let[name,cfg]of Object.entries(agents))if(stripKnownSwarmPrefix(name)==="architect"&&name!==targetName)agentConfig[name]={...isObjectRecord(cfg)?cfg:{},mode:"subagent"};let targetExisting=agentConfig[targetName],targetAgent=agents[targetName];agentConfig[targetName]={...isObjectRecord(targetExisting)?targetExisting:{},...isObjectRecord(targetAgent)?targetAgent:{},mode:"primary"}}else addDeferredWarning(`[swarm] auto_select_architect is set to "${targetName}" but that is not a known architect agent. No architect demotion applied.`)}}else addDeferredWarning("[swarm] auto_select_architect is enabled but no architect agents were found in the generated set. The option has no effect.");let shortcutDescription=(cmd)=>{let entry=COMMAND_REGISTRY[cmd];if(!entry?.description)return`Use /swarm ${cmd}`;let desc=entry.description.charAt(0).toLowerCase()+entry.description.slice(1);return`Use /swarm ${cmd} to ${desc}`};opencodeConfig.command={...opencodeConfig.command||{},swarm:{template:"/swarm $ARGUMENTS",description:(()=>{return`Swarm management commands: /swarm [${VALID_COMMANDS.filter((cmd)=>{let entry=COMMAND_REGISTRY[cmd];return!entry.aliasOf&&!entry.deprecated&&!entry.subcommandOf}).join("|")}]`})()},"swarm-status":{template:"/swarm status",description:"Use /swarm status to show current swarm status and active phase"},"swarm-show-plan":{template:"/swarm show-plan $ARGUMENTS",description:"Use /swarm show-plan to view or filter the current execution plan"},"swarm-plan":{template:"/swarm plan $ARGUMENTS",description:"Deprecated alias for /swarm show-plan"},"swarm-agents":{template:"/swarm agents",description:"Use /swarm agents to list registered swarm agents"},"swarm-history":{template:"/swarm history",description:"Use /swarm history to show completed phases summary"},"swarm-config":{template:"/swarm config $ARGUMENTS",description:"Use /swarm config to show or validate configuration"},"swarm-evidence":{template:"/swarm evidence $ARGUMENTS",description:"Use /swarm evidence to view evidence bundles and summaries"},"swarm-handoff":{template:"/swarm handoff",description:"Use /swarm handoff to prepare handoff brief for switching models mid-task"},"swarm-archive":{template:"/swarm archive",description:"Use /swarm archive to archive old evidence bundles"},"swarm-diagnose":{template:"/swarm diagnose",description:"Use /swarm diagnose to run health checks on swarm state"},"swarm-diagnosis":{template:"/swarm diagnosis",description:"Use /swarm diagnosis to run health checks on swarm state"},"swarm-preflight":{template:"/swarm preflight",description:"Use /swarm preflight to run preflight automation checks"},"swarm-sync-plan":{template:"/swarm sync-plan",description:"Use /swarm sync-plan to sync plan.json with plan.md"},"swarm-benchmark":{template:"/swarm benchmark",description:"Use /swarm benchmark to show performance metrics"},"swarm-gate-audit":{template:"/swarm gate-audit $ARGUMENTS",description:"Use /swarm gate-audit to run the bounded Tier-1 production gate matrix"},"swarm-gate-stats":{template:"/swarm gate-stats $ARGUMENTS",description:"Use /swarm gate-stats to summarize stored gate-audit evidence"},"swarm-skill-opt":{template:"/swarm skill-opt $ARGUMENTS",description:"Use /swarm skill-opt to govern skill optimization (plan|run|status|diff|approve|reject|rollback|history)"},"swarm-costs":{template:"/swarm costs $ARGUMENTS",description:"Use /swarm costs to show per-agent, task, gate, and retry token/cost totals"},"swarm-export":{template:"/swarm export",description:"Use /swarm export to export plan and context as JSON"},"swarm-reset":{template:"/swarm reset --confirm",description:"Use /swarm reset --confirm to clear swarm state (requires --confirm)"},"swarm-rollback":{template:"/swarm rollback $ARGUMENTS",description:"Use /swarm rollback to restore swarm state to a checkpoint"},"swarm-retrieve":{template:"/swarm retrieve $ARGUMENTS",description:"Use /swarm retrieve to retrieve full output from summary"},"swarm-clarify":{template:"/swarm clarify $ARGUMENTS",description:"Use /swarm clarify to clarify and refine a feature specification"},"swarm-analyze":{template:"/swarm analyze",description:"Use /swarm analyze to analyze spec vs plan for coverage gaps"},"swarm-specify":{template:"/swarm specify $ARGUMENTS",description:"Use /swarm specify to generate or import a feature specification"},"swarm-brainstorm":{template:"/swarm brainstorm $ARGUMENTS",description:"Use /swarm brainstorm to enter the architect MODE: BRAINSTORM planning workflow"},"swarm-loop":{template:"/swarm loop $ARGUMENTS",description:"Use /swarm loop <objective> to run a compound-engineering loop: brainstorm → plan → build → review → improve, iterating until done [--max-cycles 1..5] [--autonomy checkpoint|auto] [--depth standard|exhaustive] [--resume]"},"swarm-council":{template:"/swarm council $ARGUMENTS",description:"Use /swarm council <question> to convene a multi-model General Council deliberation (generalist / skeptic / domain expert) [--spec-review]"},"swarm-pr-review":{template:"/swarm pr-review $ARGUMENTS",description:"Use /swarm pr-review to launch deep PR review with multi-lane analysis"},"swarm-review":{template:"/swarm review $ARGUMENTS",description:"Use /swarm review to run the bounded whole-diff review engine for the selected local scope"},"swarm-pr-feedback":{template:"/swarm pr-feedback $ARGUMENTS",description:"Use /swarm pr-feedback to ingest and close known PR feedback (review comments, CI failures, conflicts) without a fresh broad review"},"swarm-abort-pr-workflow":{template:"/swarm abort-pr-workflow $ARGUMENTS",description:"Use /swarm abort-pr-workflow to clear a stuck PR_REVIEW/PR_FEEDBACK mechanical gate and stop the auto-resume loop (human-only escape hatch)"},"swarm-approve-plan-critic":{template:"/swarm approve-plan-critic $ARGUMENTS",description:"Use /swarm approve-plan-critic to record a MANUAL plan-critic approval that unblocks the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the snapshot was not recorded (human-only escape hatch)"},"swarm-ci-monitor":{template:"/swarm ci-monitor $ARGUMENTS",description:"Use /swarm ci-monitor to drive an already-reviewed, approved PR to green and merged (monitor CI, fix, merge)"},"swarm-pr-subscribe":{template:"/swarm pr subscribe $ARGUMENTS",description:shortcutDescription("pr subscribe")},"swarm-pr-unsubscribe":{template:"/swarm pr unsubscribe $ARGUMENTS",description:shortcutDescription("pr unsubscribe")},"swarm-pr-status":{template:"/swarm pr status",description:shortcutDescription("pr status")},"swarm-ci-simulate":{template:"/swarm ci-simulate $ARGUMENTS",description:shortcutDescription("ci-simulate")},"swarm-learning":{template:"/swarm learning",description:shortcutDescription("learning")},"swarm-post-mortem":{template:"/swarm post-mortem $ARGUMENTS",description:shortcutDescription("post-mortem")},"swarm-deep-dive":{template:"/swarm deep-dive $ARGUMENTS",description:"Use /swarm deep-dive to launch a read-only deep audit with parallel explorer waves, dual reviewers, and critic challenge"},"swarm-deep-research":{template:"/swarm deep-research $ARGUMENTS",description:"Use /swarm deep-research <question> to run a multi-source, fact-checked deep research pass and synthesize a cited report [--depth standard|exhaustive] [--max-researchers 1..6] [--rounds 1..4] [--brief]"},"swarm-codebase-review":{template:"/swarm codebase-review $ARGUMENTS",description:"Use /swarm codebase-review to launch codebase-review-swarm for a quote-grounded full-repo or large-subsystem audit"},"swarm-design-docs":{template:"/swarm design-docs $ARGUMENTS",description:"Use /swarm design-docs to generate or sync language-agnostic design docs for the project under build"},"swarm-sdd":{template:"/swarm sdd $ARGUMENTS",description:"Use /swarm sdd to inspect OpenSpec-compatible SDD artifacts"},"swarm-sdd-status":{template:"/swarm sdd status",description:"Use /swarm sdd status to show effective spec and OpenSpec artifact status"},"swarm-sdd-validate":{template:"/swarm sdd validate $ARGUMENTS",description:"Use /swarm sdd validate to validate OpenSpec-compatible SDD artifacts"},"swarm-sdd-project":{template:"/swarm sdd project $ARGUMENTS",description:"Use /swarm sdd project to materialize OpenSpec artifacts into .swarm/spec.md"},"swarm-issue":{template:"/swarm issue $ARGUMENTS",description:"Use /swarm issue to ingest a GitHub issue into the swarm workflow"},"swarm-qa-gates":{template:"/swarm qa-gates $ARGUMENTS",description:"Use /swarm qa-gates to view or modify QA gate profile for the current plan"},"swarm-dark-matter":{template:"/swarm dark-matter",description:"Use /swarm dark-matter to detect hidden file couplings"},"swarm-knowledge":{template:"/swarm knowledge $ARGUMENTS",description:"Use /swarm knowledge for knowledge management (quarantine/restore/migrate)"},"swarm-memory":{template:"/swarm memory $ARGUMENTS",description:"Use /swarm memory for memory status, JSONL export/import, and SQLite migration"},"swarm-memory-status":{template:"/swarm memory status",description:"Use /swarm memory status to show provider and migration status"},"swarm-memory-export":{template:"/swarm memory export",description:"Use /swarm memory export to write current memory to JSONL"},"swarm-memory-import":{template:"/swarm memory import",description:"Use /swarm memory import to import legacy JSONL into SQLite"},"swarm-memory-migrate":{template:"/swarm memory migrate",description:"Use /swarm memory migrate to run the one-time SQLite migration"},"swarm-curate":{template:"/swarm curate",description:"Use /swarm curate to curate knowledge artifacts and entries"},"swarm-consolidate":{template:"/swarm consolidate $ARGUMENTS",description:"Use /swarm consolidate to run quota-bounded skill-improver consolidation"},"swarm-concurrency":{template:"/swarm concurrency $ARGUMENTS",description:"Use /swarm concurrency to manage runtime concurrency override for plan execution"},"swarm-turbo":{template:"/swarm turbo",description:"Use /swarm turbo to enable turbo mode for faster execution"},"swarm-epic":{template:"/swarm epic $ARGUMENTS",description:shortcutDescription("epic")},"swarm-coupling":{template:"/swarm coupling $ARGUMENTS",description:shortcutDescription("coupling")},"swarm-lanes":{template:"/swarm lanes",description:shortcutDescription("lanes")},"swarm-guardrail-explain":{template:"/swarm guardrail explain $ARGUMENTS",description:shortcutDescription("guardrail explain")},"swarm-guardrail-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-context-map-stats":{template:"/swarm context-map stats",description:shortcutDescription("context-map-stats")},"swarm-link":{template:"/swarm link $ARGUMENTS",description:"Use /swarm link to link this worktree to a shared knowledge store [name|status]"},"swarm-unlink":{template:"/swarm unlink $ARGUMENTS",description:"Use /swarm unlink to unlink this worktree from the shared knowledge store [--no-copy]"}},log("Config applied",{agents:Object.keys(agents),commands:["swarm"]})},"experimental.chat.messages.transform":composeHandlers(...[(_input,output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform START");let mctx=resolveMessageTransformContext(output);if(mctx.sessionID){let archAgent=swarmState.activeAgent.get(mctx.sessionID),archSession=swarmState.agentSessions.get(mctx.sessionID),agentName=archAgent??archSession?.agentName??"";if(stripKnownSwarmPrefix(agentName)===ORCHESTRATOR_NAME)try{delegationLedgerHook.onArchitectResume(mctx.sessionID)}catch{}}return Promise.resolve()},pipelineHook["experimental.chat.messages.transform"],contextBudgetHandler,initOrphanRecoveryAdvisoryHook.messagesTransform,durableBackgroundAdvisoryMessagesTransform,fullAutoInterceptHook?.messagesTransform,ccCommandInterceptHook?.messagesTransform,delegationGateHooks.messagesTransform,issueTraceHook.messagesTransform,delegationSanitizerHook,memoryLifecycleHooks.messagesTransform,knowledgeInjectorHook,(_input,output)=>{try{let mctx=resolveMessageTransformContext(output);return knowledgeApplicationTransformScan(ctx.directory,output,mctx.sessionID)}catch{return Promise.resolve()}},(_input,output)=>{try{if(!skillPropagationConfig.enabled)return Promise.resolve();let mctx=resolveMessageTransformContext(output);return skillPropagationTransformScan(ctx.directory,output,mctx.sessionID,skillPropagationConfig)}catch{return Promise.resolve()}},(_input,output)=>{if(Array.isArray(output.messages))consolidateSystemMessagesInPlace(output.messages);if(process.env.DEBUG_SWARM)console.error("[DIAG] messagesTransform DONE");return Promise.resolve()}].filter((fn2)=>Boolean(fn2))),"experimental.text.complete":prWorkflowResponseGate.textComplete,"experimental.chat.system.transform":composeHandlers(...[async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform START")},systemEnhancerHook["experimental.chat.system.transform"],async(_input,_output)=>{if(process.env.DEBUG_SWARM)console.error("[DIAG] systemTransform enhancer DONE")},contextCapsuleInjectHook["experimental.chat.system.transform"],(input,_output)=>{try{let{sessionID}=input;if(!sessionID)return Promise.resolve();let lastTime=_heartbeatTimers.get(sessionID);if(Date.now()-(lastTime??0)>30000)_heartbeatTimers.set(sessionID,Date.now()),capSessionMap(_heartbeatTimers,MAX_TRACKED_HEARTBEAT_SESSIONS),telemetry.heartbeat(sessionID)}catch{}return Promise.resolve()},automationConfig.capabilities?.phase_preflight===!0&&preflightTriggerManager?createPhaseMonitorHook(ctx.directory,preflightTriggerManager,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):knowledgeConfig.enabled?createPhaseMonitorHook(ctx.directory,void 0,void 0,(sessionId)=>createCuratorLLMDelegate(ctx.directory,"init",sessionId)):void 0,swarmCommandSystemRuleHook,roleFilterSystemHook["experimental.chat.system.transform"]].filter(Boolean)),"experimental.session.compacting":compactionHook["experimental.session.compacting"],"command.execute.before":safeHook(commandHandler),"tool.execute.before":async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] toolBefore tool=${normalizeToolName(input.tool)??input.tool} session=${input.sessionID}`);if(!swarmState.activeAgent.has(input.sessionID))swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME);let session=swarmState.agentSessions.get(input.sessionID),activeAgent=swarmState.activeAgent.get(input.sessionID);if(session&&activeAgent&&activeAgent!==ORCHESTRATOR_NAME){if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME){if(!session.delegationActive&&Date.now()-session.lastAgentEventTime>1e4)swarmState.activeAgent.set(input.sessionID,ORCHESTRATOR_NAME),ensureAgentSession(input.sessionID,ORCHESTRATOR_NAME)}}let failClosedRegionCompleted=!1;try{await guardrailsHooks.toolBefore(input,output),await scopeGuardHook.toolBefore(input,output);let prWorkflowControllerSessionID=await prWorkflowSessionResolver.resolve(input.sessionID),prWorkflowToolContext=resolveToolBeforeContext(input,output);await enforcePrWorkflowToolBefore(ctx.directory,prWorkflowControllerSessionID,normalizeToolName(input.tool)??input.tool,prWorkflowToolContext.args??void 0,instanceGeneratedAgentNames),await delegationGateHooks.toolBefore(input,output),await fullAutoDelegationHook.toolBefore(input,output),await fullAutoPermissionHook.toolBefore(input,output),await knowledgeApplicationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID},KnowledgeApplicationConfigSchema.parse(config3.knowledge_application??{}));let skillResult=await skillPropagationGateBefore(ctx.directory,{tool:input.tool,agent:resolveToolBeforeContext(input,output).agent,sessionID:input.sessionID,args:resolveToolBeforeContext(input,output).args??void 0},skillPropagationConfig);if(skillResult.blocked)throw Error(skillResult.reason??"Blocked by skill propagation gate");if(skillResult.reason){let skillSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);pushAdvisory(skillSession,skillResult.reason)}let toolBeforeCtx=resolveToolBeforeContext(input,output),toolBeforeArgs=toolBeforeCtx.args??{};if(injectSkillsIntoDelegation(ctx.directory,toolBeforeArgs,skillResult.recommendedSkills,stripKnownSwarmPrefix(parseDelegationArgs(toolBeforeArgs)?.targetAgent??"")||toolBeforeCtx.agent,input.sessionID,{quiet:config3.quiet}),failClosedRegionCompleted=!0,knowledgeConfig.enabled)await injectDelegateDirectivesBefore(ctx.directory,{tool:input.tool,agent:toolBeforeCtx.agent,sessionID:input.sessionID,args:toolBeforeArgs},knowledgeConfig);setStoredInputArgs(input.callID,output.args);let pressurePct=getSessionBudgetPct(input.sessionID);if(pressurePct>=50){let pressureSession=ensureAgentSession(input.sessionID,swarmState.activeAgent.get(input.sessionID)??ORCHESTRATOR_NAME);if(!pressureSession.contextPressureWarningSent)pressureSession.contextPressureWarningSent=!0,pushAdvisory(pressureSession,`CONTEXT PRESSURE: ${pressurePct.toFixed(1)}% of context window used. Prioritize completing the current task before starting new work.`)}if(autoReviewConfig.enabled)await beginApprovedReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:toolBeforeArgs,parentSessionID:input.sessionID,callID:input.callID,maxBytes:autoReviewConfig.max_diff_kb*1024});await safeHook(activityHooks.toolBefore)(input,output),await reserveApprovedPhaseParticipation({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,args:toolBeforeArgs,policy:config3.phase_complete}),resetGateDenialStreaks(input.sessionID,input.tool,toolBeforeArgs);{let beforeToolNormalized=normalizeToolName(input.tool)??input.tool;if(beforeToolNormalized==="Task"||beforeToolNormalized==="task"){let delegatedAgent=typeof toolBeforeArgs.subagent_type==="string"&&toolBeforeArgs.subagent_type.length>0?toolBeforeArgs.subagent_type:swarmState.activeAgent.get(input.sessionID)??"unknown",delegationTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??"";_delegationTelemetryByCallID.set(input.callID,{agentName:delegatedAgent,taskId:delegationTaskId}),capSessionMap(_delegationTelemetryByCallID,MAX_TRACKED_DELEGATION_TELEMETRY),telemetry.delegationBegin(input.sessionID,delegatedAgent,delegationTaskId)}}}catch(err2){if(!failClosedRegionCompleted){let deniedMessage=err2&&typeof err2==="object"&&typeof err2.message==="string"?err2.message:null,deniedArgs;try{deniedArgs=resolveToolBeforeContext(input,output).args??void 0}catch{deniedArgs=void 0}if(deniedMessage!==null&&!isAbortLikeError(err2))try{await recordDeniedToolCall(input.sessionID,{tool:input.tool,callID:input.callID,args:deniedArgs},deniedMessage,ctx.directory,{maxLines:1000})}catch{}noteGateDenial(input.sessionID,input.tool,err2,{enabled:guardrailsConfig.enabled,warnThreshold:guardrailsConfig.gate_denial_warn_threshold,stopThreshold:guardrailsConfig.gate_denial_stop_threshold},deniedArgs)}if(!failClosedRegionCompleted&&(normalizeToolName(input.tool)==="Task"||normalizeToolName(input.tool)==="task"))try{await delegationGateHooks.abortDeniedSettlementForCall(input.callID)}catch{}throw err2}},"tool.execute.after":async(input,output)=>{let _dbg=!!process.env.DEBUG_SWARM,_toolName=normalizeToolName(input.tool)??input.tool;if(_dbg)console.error(`[DIAG] toolAfter START tool=${_toolName} session=${input.sessionID}`);let normalizedTool=normalizeToolName(input.tool),isTaskTool8=normalizedTool==="Task"||normalizedTool==="task",afterCtx=resolveToolAfterContext(input);if(autoReviewConfig.enabled&&isTaskTool8)await completeReviewerScopeLifecycle({directory:ctx.directory,tool:input.tool,args:afterCtx.args,output,parentSessionID:input.sessionID,callID:input.callID});let hookChain=async()=>{if(await activityHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter activity done tool=${_toolName}`);if(await safeHook(trajectoryLoggerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter trajectoryLogger done tool=${_toolName}`);if(knowledgeConfig.enabled)await safeHook(()=>collectDelegateAcksAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>collectReviewerVerdictsAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,args:afterCtx.args},output))(input,output),await safeHook(()=>microReflectorAfter(ctx.directory,input,output,createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window},{enabled:learningConfig.realtime_admission.enabled,maxQueueSize:learningConfig.realtime_admission.max_queue_size}))(input,output);if(await safeHook(async()=>{let summary=await realtimeAdmissionAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID},learningConfig.realtime_admission,async()=>{let plan=await loadPlan(ctx.directory).catch(()=>null);return{knowledgeConfig,projectName:plan?.title??"unknown",phaseNumber:plan?.current_phase??1,sessionID:input.sessionID,llmDelegate:createCuratorLLMDelegate(ctx.directory,"phase",input.sessionID),onKnowledgeChanged:bumpKnowledgeGeneration}});if(summary)log("realtime admission drain",{sessionID:input.sessionID,...summary})})(input,output),await safeHook(async()=>{await collectReviewerReceiptAfter(ctx.directory,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,args:afterCtx.args},output,{dispatcher:reviewModelDispatcher,config:autoReviewConfig,generatedAgentNames:instanceGeneratedAgentNames,agentModelRegistry:reviewAgentModelRegistry,injectAdvisory:advisoryInjector,validationScheduler:findingValidationScheduler})})(input,output),await safeHook(autoReviewHook.toolAfter)(input,afterCtx),await safeHook(prmHook.toolAfter)(input,output),await guardrailsHooks.toolAfter(input,output),_dbg)console.error(`[DIAG] toolAfter guardrails done tool=${_toolName}`);if(await safeHook(delegationLedgerHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter ledger done tool=${_toolName}`);if(await safeHook(selfReviewHook.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter selfReview done tool=${_toolName}`);if(await safeHook(memoryLifecycleHooks.toolAfter)(input,output),_dbg)console.error(`[DIAG] toolAfter memory done tool=${_toolName}`);if(await safeHook(delegationGateHooks.toolAfter)(input,output),await safeHook(async()=>{await observePhaseParticipationToolResult({directory:ctx.directory,tool:input.tool,parentSessionId:input.sessionID,callId:input.callID,output})})(input,output),_dbg)console.error(`[DIAG] toolAfter delegationGate done tool=${_toolName}`);if(await safeHook(fullAutoInputProbeHook.toolAfter)(input,output),await safeHook(fullAutoDelegationHook.toolAfter)(input,output),await safeHook(prAutoSubscribeHook.toolAfter)(input,output),isTaskTool8&&typeof output.output==="string")try{let adversarialMatches=detectAdversarialPatterns(output.output);if(adversarialMatches.length>0){let sessionId=input.sessionID,session=swarmState.agentSessions.get(sessionId);if(session)pushAdvisory(session,`ADVERSARIAL PATTERN DETECTED: ${adversarialMatches.map((p)=>p.pattern).join(", ")}. Review agent output for potential prompt injection or gate bypass.`);if("adversarialPatternDetected"in telemetry)telemetry.adversarialPatternDetected(input.sessionID,adversarialMatches)}}catch{}try{recordToolCall(normalizedTool,resolveToolAfterContext(input).args,input.sessionID)}catch{}try{let spiralMatch=await detectDebuggingSpiral(ctx.directory,input.sessionID);if(spiralMatch){let taskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??`session-${input.sessionID.slice(0,12)}`,spiralResult=await handleDebuggingSpiral(spiralMatch,taskId,ctx.directory),session=swarmState.agentSessions.get(input.sessionID);if(session)pushAdvisory(session,spiralResult.message)}}catch{}if(knowledgeCuratorHook)await safeHook(knowledgeCuratorHook)(input,output);if(hivePromoterHook)await safeHook(hivePromoterHook)(input,output);if(_dbg)console.error(`[DIAG] toolAfter knowledge done tool=${_toolName}`);if(await safeHook(steeringConsumedHook)(input,output),await safeHook(coChangeSuggesterHook)(input,output),await safeHook(darkMatterDetectorHook)(input,output),_dbg)console.error(`[DIAG] toolAfter intelligence done tool=${_toolName}`);if(await snapshotWriterHook(input,output),await toolSummarizerHook?.(input,output),_dbg)console.error(`[DIAG] toolAfter snapshot+summarizer done tool=${_toolName}`);let execMode=config3.execution_mode??"balanced";if(execMode==="strict"){if(slopDetectorHook)await slopDetectorHook.toolAfter(input,output);if(incrementalVerifyHook)await incrementalVerifyHook.toolAfter(input,output)}if(execMode!=="fast"&&compactionServiceHook)await compactionServiceHook.toolAfter(input,output);if(repoGraphHook)await safeHook(repoGraphHook.toolAfter)(input,output);if(isTaskTool8&&config3.context_map?.enabled===!0&&input.sessionID)try{let contextMapTaskId=swarmState.agentSessions.get(input.sessionID)?.currentTaskId??null;if(contextMapTaskId){let agentOutput=typeof output.output==="string"?output.output:"";updateContextMapAfterAgent({task_id:contextMapTaskId,agent_role:swarmState.activeAgent.get(input.sessionID)??"unknown",files_touched:[],implementation_summary:agentOutput.slice(0,500),task_goal:"",final_status:"completed",directory:ctx.directory})}}catch{}let toolOutputConfig=config3.tool_output;if(toolOutputConfig&&toolOutputConfig.truncation_enabled!==!1&&typeof output.output==="string"){let defaultTruncatableTools=new Set(["diff","symbols","bash","shell","test_runner","lint","pre_check_batch","complexity_hotspots","pkg_audit","sbom_generate","schema_drift"]),configuredTools=toolOutputConfig.truncation_tools,truncatableTools=computeEffectiveTruncatableTools(defaultTruncatableTools,configuredTools),maxLines=toolOutputConfig.per_tool?.[input.tool]??toolOutputConfig.max_lines??150;if(truncatableTools.has(input.tool))output.output=truncateToolOutput(output.output,maxLines,input.tool,10)}};try{await hookChain()}catch(err2){let warning=`[swarm] toolAfter hook chain error tool=${_toolName}: ${err2 instanceof Error?err2.message:String(err2)}`;if(!config3.quiet)console.warn(warning);else addDeferredWarning(warning)}if(isTaskTool8){let backgroundResultIsRunning=outputLooksLikeBackgroundRunning(output),sessionId=input.sessionID,beganDelegation=_delegationTelemetryByCallID.get(input.callID),storedSubagentType=typeof afterCtx.args?.subagent_type==="string"?afterCtx.args.subagent_type:void 0,agentName=beganDelegation?.agentName||storedSubagentType||swarmState.activeAgent.get(sessionId)||"unknown",baseAgentName=stripKnownSwarmPrefix(agentName),preHandoffSession=swarmState.agentSessions.get(sessionId),activeWindow=getActiveWindow(sessionId),configuredModel=resolveRegisteredAgentModel(config3,agentName)??DEFAULT_MODELS[baseAgentName]??DEFAULT_MODELS.default,assistantUsage=consumeAssistantUsageForTask(sessionId,output),costFields=buildDelegationCostFields({raw:{metadata:output.metadata,output,assistant:assistantUsage},model:configuredModel,gate:preHandoffSession?.lastDelegationReason,retry_index:activeWindow?.transientRetryCount,pricing:config3.pricing});swarmState.activeAgent.set(sessionId,ORCHESTRATOR_NAME),ensureAgentSession(sessionId,ORCHESTRATOR_NAME);let taskSession=swarmState.agentSessions.get(sessionId);if(taskSession){if(taskSession.delegationActive=!1,taskSession.lastAgentEventTime=Date.now(),!backgroundResultIsRunning){if(_delegationTelemetryByCallID.delete(input.callID),telemetry.delegationEnd(sessionId,agentName,beganDelegation?.taskId||taskSession.currentTaskId||"","completed",costFields),baseAgentName==="reviewer"||baseAgentName==="test_engineer"||baseAgentName==="critic"||baseAgentName==="critic_sounding_board")pushAdvisory(taskSession,`[PIPELINE] ${baseAgentName} delegation complete for task ${taskSession.currentTaskId??"unknown"}. `+"Resume the QA gate pipeline — check your task pipeline steps for the next required action. "+"Do not stop here.");if(baseAgentName==="critic_sounding_board"){let rawResponse=typeof output.output==="string"?output.output:"",parsed=parseSoundingBoardResponse(rawResponse);if(parsed){let verdictMsg=`[SOUNDING_BOARD] Verdict: ${parsed.verdict}. ${parsed.reasoning}`;if(parsed.improvedQuestion)verdictMsg+=` Rephrase to: ${parsed.improvedQuestion}`;if(parsed.answer)verdictMsg+=` Answer: ${parsed.answer}`;if(parsed.warning)verdictMsg+=` WARNING: ${parsed.warning}`;pushAdvisory(taskSession,verdictMsg),taskSession.lastDelegationReason="critic_consultation"}else pushAdvisory(taskSession,`[SOUNDING_BOARD] WARNING: Could not parse a structured verdict from critic_sounding_board response (${rawResponse.length} chars). `+"Treat as REPHRASE — review the raw response before surfacing to user or escalating. "+"Do not silently accept as resolved.")}}}if(_dbg)console.error(`[DIAG] Task handoff DONE session=${sessionId} activeAgent=${swarmState.activeAgent.get(sessionId)}`)}if(deleteStoredInputArgs(input.callID),_dbg)console.error(`[DIAG] toolAfter COMPLETE tool=${_toolName}`)},"chat.message":safeHook(async(input,output)=>{if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message agent=${input.agent??"none"} session=${input.sessionID}`);if(await delegationHandler(input,output),input?.sessionID)try{await cacheCohortIdAtMessage(ctx.directory,input.sessionID)}catch{}try{if(input?.sessionID&&input?.agent){if(stripKnownSwarmPrefix(String(input.agent))==="architect")tickAndMaybeDispatchCadence(ctx.directory,input.sessionID,"architectTurns",config3,{activeAgent:String(input.agent)})}}catch{}if(process.env.DEBUG_SWARM)console.error(`[DIAG] chat.message DONE agent=${input.agent??"none"}`)}),automation:automationManager}}var src_default={id:"opencode-swarm",server:OpenCodeSwarm};export{schedulePostResolutionTasksForTest,recordTestImpactGateGroundTruth,overrideIndexInternalsForTest,loadTier1EvaluationTasks,evaluationV1,evaluatePrReviewRecoveryV1,evaluateCandidateV1,src_default as default,computeEffectiveTruncatableTools,capSessionMap,archiveSqliteSnapshot,_resetDelegationTelemetryPairingForTesting};