opencode-swarm 7.139.6 → 7.139.7

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/.opencode/skills/swarm-pr-review/SKILL.md +62 -6
  2. package/.opencode/skills/swarm-pr-review/references/prompt-templates.md +44 -6
  3. package/dist/agents/explorer.d.ts +1 -1
  4. package/dist/cli/{config-doctor-7v9at76j.js → config-doctor-pc48vfzg.js} +2 -2
  5. package/dist/cli/{curation-policy-rbrx3kd2.js → curation-policy-2rh3zysm.js} +2 -2
  6. package/dist/cli/{curator-llm-factory-305cfcxz.js → curator-llm-factory-de10hnhj.js} +13 -13
  7. package/dist/cli/{curator-bdc5hssa.js → curator-tm9rp9yx.js} +13 -13
  8. package/dist/cli/{explorer-swjc297z.js → explorer-e9h66egs.js} +1 -1
  9. package/dist/cli/{guardrail-explain-w9rwgz4c.js → guardrail-explain-979dxbd5.js} +14 -14
  10. package/dist/cli/{guardrail-log-4805jgj5.js → guardrail-log-wxa8janm.js} +3 -3
  11. package/dist/cli/{hive-promoter-jrd4pjb6.js → hive-promoter-w4ezne1c.js} +13 -13
  12. package/dist/cli/{index-k5z14rb1.js → index-3r61js2q.js} +2 -2
  13. package/dist/cli/{index-wv89xmbe.js → index-3w0kxqyy.js} +1 -1
  14. package/dist/cli/{index-8d2d7c6k.js → index-4tjk6k4a.js} +2 -2
  15. package/dist/cli/{index-t94f72tb.js → index-6d60gctc.js} +2 -2
  16. package/dist/cli/{index-1tw24kcp.js → index-7f4jhdhw.js} +1 -1
  17. package/dist/cli/{index-n3ppm2gt.js → index-92j14gdt.js} +1 -1
  18. package/dist/cli/{index-m7xks4r4.js → index-cp592623.js} +4 -4
  19. package/dist/cli/{index-a6v3kzyc.js → index-f7wq4q9r.js} +5 -5
  20. package/dist/cli/{index-ev72jrxc.js → index-j0gy1ggg.js} +1 -1
  21. package/dist/cli/{index-3fscvmfw.js → index-k4tcdnvd.js} +3 -3
  22. package/dist/cli/{index-68gh7p3t.js → index-n4x9racs.js} +1 -1
  23. package/dist/cli/{index-h7ht03c4.js → index-nxs7r6sd.js} +39 -39
  24. package/dist/cli/{index-7qx874pn.js → index-rvr1p73g.js} +1 -1
  25. package/dist/cli/{index-b6k9z88b.js → index-sd7ajhb5.js} +1 -1
  26. package/dist/cli/{index-fjrt81db.js → index-ssjm3458.js} +1 -1
  27. package/dist/cli/{index-6mjf4vr1.js → index-v2xrer41.js} +16 -29
  28. package/dist/cli/{index-sfbwze80.js → index-vx6mwms2.js} +15 -15
  29. package/dist/cli/index.js +13 -13
  30. package/dist/cli/{knowledge-escalator-7z9vwqrk.js → knowledge-escalator-kyejsd7z.js} +3 -3
  31. package/dist/cli/{knowledge-events-vw2cdtnp.js → knowledge-events-n5z7w8x2.js} +1 -1
  32. package/dist/cli/{knowledge-store-ecv0qs7r.js → knowledge-store-s65wnc1m.js} +1 -1
  33. package/dist/cli/{knowledge-validator-arppnzpb.js → knowledge-validator-cgtmhqya.js} +4 -4
  34. package/dist/cli/{scan-cursor-7740wg6r.js → scan-cursor-6z3rbdxp.js} +2 -2
  35. package/dist/cli/{schema-sajt4mcv.js → schema-fvj8smjz.js} +1 -1
  36. package/dist/cli/{skill-generator-k8qz8ja5.js → skill-generator-9kzsefn1.js} +5 -5
  37. package/dist/hooks/pr-workflow-gate.d.ts +2 -2
  38. package/dist/index.js +63 -58
  39. package/dist/tools/dispatch-lanes.d.ts +3 -6
  40. 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.139.6",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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","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:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",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.139.7",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},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","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:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",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
 
@@ -1293,37 +1293,24 @@ src/tools/declare-scope.ts — function has 12 parameters, consider splitting; t
1293
1293
  Activates when your prompt contains "[CANDIDATE]" anywhere in its text.
1294
1294
 
1295
1295
  When active, replace the default OUTPUT FORMAT above with structured pipe-delimited
1296
- candidate rows. Emit the marker-bearing header, then exactly one unprefixed data
1297
- row per finding:
1298
-
1299
- [CANDIDATE] | candidate_id | lane | severity | category | file:line | claim | evidence_summary | impact_context | confidence
1300
-
1301
- Field rules:
1302
- - candidate_id: unique within this lane (e.g. C-001, C-002)
1303
- - lane: your lane name or focus area
1304
- - severity: INFO | LOW | MEDIUM | HIGH | CRITICAL
1305
- - category: short category tag (e.g. null-safety, async-ordering, injection)
1306
- - file:line: exact file path and line number (e.g. src/utils/cache.ts:142)
1307
- - claim: one-sentence description of the issue
1308
- - evidence_summary: what you observed in the code that supports the claim
1309
- - impact_context: who or what is affected downstream
1310
- - confidence: LOW | MEDIUM | HIGH
1311
-
1312
- Emit a header row first, then one unprefixed data row per finding. Use pipe (|) to
1313
- separate fields; escape literal pipe characters inside field values as \\|.
1314
-
1315
- If either a standard explorer or a micro-lane finds zero issues, emit the
1316
- header followed by exactly the matching family form:
1317
- [CLEAN] | lane | coverage_scope | evidence
1318
- [CLEAN] | micro_lane | coverage_scope | evidence
1319
- Replace lane or micro_lane with the exact controller-assigned value and fill
1320
- the remaining fields with the checks completed and concrete negative evidence.
1321
- Header-only output is unattested. Do NOT fall back to the default
1296
+ candidate rows. Treat the exact header supplied by the caller or controller as
1297
+ the single authoritative schema. Copy the marker-bearing header verbatim, then
1298
+ emit exactly one unprefixed data row per finding. Do not merge fields from
1299
+ another candidate family or invent a trailing field.
1300
+
1301
+ Use the exact caller-assigned lane identity. Candidate severity is INFO, LOW,
1302
+ MEDIUM, HIGH, or CRITICAL; confidence is exactly LOW, MEDIUM, or HIGH. Escape a
1303
+ literal pipe inside a field as \\|. Emit machine rows as plain text, never inside
1304
+ Markdown code fences.
1305
+
1306
+ For zero findings, copy the exact matching [CLEAN] template supplied by the
1307
+ caller and replace its placeholders with the controller-assigned lane, a
1308
+ substantive coverage scope, and concrete negative evidence. A CLEAN row has no
1309
+ confidence or trailing field. Header-only output is unattested. If the prompt
1310
+ contains the marker but no exact candidate header and CLEAN template, report the
1311
+ missing contract instead of guessing. Do NOT fall back to the default
1322
1312
  PROJECT/STRUCTURE format.
1323
1313
 
1324
- For micro-lane dispatches, use the micro-lane variant:
1325
- [CANDIDATE] | candidate_id | micro_lane | severity | category | file:line | claim | invariant_violated | evidence_summary | confidence
1326
-
1327
1314
  Do NOT use CONFIRMED, DISPROVED, or PRE_EXISTING — those are reviewer verdicts.
1328
1315
 
1329
1316
  ## INTEGRATION IMPACT ANALYSIS MODE
@@ -3215,7 +3202,7 @@ HARD CONSTRAINTS (apply regardless of skill load success):
3215
3202
  - RUN ALL BASE LANES: the default PR_REVIEW path always launches exactly six repository-agnostic base check-type lanes from the skill. Use \`mode: "swarm-pr-review:base"\` and the exact six \`workflow_lane\` identifiers. The runtime rejects partial, duplicate, or mislabelled waves. Do not collapse, omit, or scale down the base lanes for a small, docs-only, or CI-only PR.
3216
3203
  - RETRY STRUCTURALLY: retry only failed base obligations in later \`swarm-pr-review:base\` async batches with the same exact \`pr_head_sha\`. Blocking \`dispatch_lanes\` and direct Task explorer/reviewer/critic dispatch are not provenance-equivalent and are rejected.
3217
3204
  - USE ASYNC DISPATCH WITHOUT IDLING: launch the base lanes with one \`dispatch_lanes_async\` call when available, record the \`batch_id\`, then keep doing non-dependent architect work while they run. Poll with \`collect_lane_results\` without \`wait\` (or \`wait: false\`) to process settled lanes and continue independent work between polls; use \`wait: true\` only as the final join when no independent work remains.
3218
- - EVALUATE ALL RISK FAMILIES: after the base explorer lanes settle, evaluate every repository-agnostic trigger row against the exact diff/context pack. Record applicable families as \`MATCHED\` and inapplicable families as provenance-free \`NOT_TRIGGERED\` with concrete absence evidence; \`unclassified-risk\` always remains \`MATCHED\`. Launch \`swarm-pr-review:micro\` lanes only for the \`MATCHED\` IDs, pass the complete exact eleven-row \`trigger_evaluation\` to every batch, and use each dispatched trigger ID as \`workflow_lane\`. Missing an evaluation row or a matched-family attestation is BLOCKED; a \`NOT_TRIGGERED\` family must not create a micro artifact.
3205
+ - EVALUATE ALL RISK FAMILIES: after the base explorer lanes settle, evaluate every repository-agnostic trigger row against the exact diff/context pack. Record applicable families as \`MATCHED\` and inapplicable families as provenance-free \`NOT_TRIGGERED\` with concrete absence evidence; \`unclassified-risk\` always remains \`MATCHED\`. Launch \`swarm-pr-review:micro\` lanes only for the \`MATCHED\` IDs. The first micro dispatch MUST pass the complete exact eleven-row \`trigger_evaluation\`, which freezes it for this session; any subsequent same-session micro batch may omit it and reuse the frozen ledger, while an explicitly supplied copy must remain exactly identical. Use each dispatched trigger ID as \`workflow_lane\`. Missing an evaluation row or a matched-family attestation is BLOCKED; a \`NOT_TRIGGERED\` family must not create a micro artifact.
3219
3206
  - RUN HEAD-BOUND VALIDATION: dispatch independent reviewers with \`mode: "swarm-pr-review:reviewer"\` and critics with \`mode: "swarm-pr-review:critic"\`, unique \`workflow_lane\` obligations, role-correct agents, and the same exact \`pr_head_sha\`. Critic dispatch is blocked until all declared reviewer obligations have successful artifacts.
3220
3207
  - COMPLETE EXPLICITLY: after final artifacts and synthesis, call \`complete_pr_workflow\` with \`mode: "PR_REVIEW"\` and the bound \`pr_head_sha\`; never leave the session trapped in a stale workflow gate.
3221
3208
  - ABORT IF UNRECOVERABLE: if the PR head cannot be fetched/checked out (the working tree stays on the wrong branch), a compound \`git fetch && git checkout\` keeps being rejected as read-only shell syntax (run them as TWO separate standalone commands first), or the merge-base bind is unreachable for any reason, call \`abort_pr_workflow\` with \`mode: "PR_REVIEW"\` and a one-line \`reason\` instead of looping. The tool refuses while PR workflow lanes are in flight (collect their results first). Aborting clears the durable gate and stops the auto-resume loop; the user can also run \`/swarm abort-pr-workflow\`. Do NOT abort as a shortcut to avoid coverage obligations — only when the bind/checkout path is genuinely unreachable.
@@ -6366,44 +6353,62 @@ ${memberLines}`,`**Rounds:** ${roundsCompleted}`,"","### Consensus",consensusBlo
6366
6353
  `);for(let line of contractDiffLines){for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){hasContractChanges2=!0;break}if(hasContractChanges2)break}}catch{hasContractChanges2=!0}let result2={files,contractChanges:[],hasContractChanges:hasContractChanges2,summary:`${files.length} files changed (summary only)`};return JSON.stringify(result2,null,2)}let fullDiffOutput=child_process12.execFileSync("git",fullDiffArgs,{encoding:"utf-8",timeout:DIFF_TIMEOUT_MS,maxBuffer:MAX_BUFFER_BYTES,cwd:directory,stdio:["ignore","pipe","pipe"]}),contractChanges=[],diffLines=fullDiffOutput.split(`
6367
6354
  `),currentFile="";for(let line of diffLines){let gitLineMatch=line.match(/^diff --git.* b\/(.+)$/);if(gitLineMatch)currentFile=gitLineMatch[1];for(let pattern of CONTRACT_PATTERNS)if(pattern.test(line)){let trimmed=line.trim();if(currentFile)contractChanges.push(`[${currentFile}] ${trimmed}`);else contractChanges.push(trimmed);break}}let hasContractChanges=contractChanges.length>0,fileCount=files.length,astDiffs=[],filesForAST=files.slice(0,MAX_AST_FILES);for(let file3 of filesForAST)try{let oldContent,newContent;if(base==="staged"){let oldRef=`HEAD:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`:${file3.path}`)}else if(base==="unstaged"){let oldRef=`:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=fs143.readFileSync(path254.join(directory,file3.path),"utf-8")}else{let oldRef=`${base}:${file3.path}`;oldContent=fileExistsInRef(oldRef)?getContentFromRef(oldRef):"",newContent=getContentFromRef(`HEAD:${file3.path}`)}let astResult=await computeASTDiff(file3.path,oldContent,newContent);if(astResult&&(astResult.changes.length>0||astResult.error))astDiffs.push(astResult)}catch(e){if(e&&typeof e==="object"&&"code"in e){if(e.code==="ENOENT")throw e}astDiffs.push({filePath:file3.path,language:null,changes:[{type:"modified",category:"other",name:"(parse failed)",lineStart:0,lineEnd:0}],durationMs:0,usedAST:!1,error:"AST parse unavailable — tree-sitter analysis failed for this file"})}let semanticSummary;if(astDiffs.length>0)try{let classifiedChanges=classifyChanges(astDiffs);semanticSummary=generateSummary(classifiedChanges)}catch{}let markdownSummary;if(semanticSummary)try{markdownSummary=generateSummaryMarkdown(semanticSummary)}catch{}let astSkippedCount=files.length>MAX_AST_FILES?files.length-MAX_AST_FILES:0,summary=diffLines.length>MAX_DIFF_LINES?`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}. (truncated to ${MAX_DIFF_LINES} lines)`:`${fileCount} files changed. Contract changes: ${hasContractChanges?"YES":"NO"}`,result={files,contractChanges,hasContractChanges,summary,...astDiffs.length>0?{astDiffs}:{},...semanticSummary?{semanticSummary}:{},...markdownSummary?{markdownSummary}:{},...astSkippedCount>0?{astSkippedCount}:{}};return JSON.stringify(result,null,2)}catch(e){let errorResult={error:e instanceof Error?`git diff failed: ${e.message}`:"git diff failed: unknown error",files:[],contractChanges:[],hasContractChanges:!1};return JSON.stringify(errorResult,null,2)}}});init_zod();import*as child_process13 from"node:child_process";import*as fs144 from"node:fs";import*as path255 from"node:path";init_git_binary_missing_error();init_create_tool();init_resolve_working_directory();async function execGit2(workingDir,args2,options){try{return await new Promise((resolve101,reject2)=>{let execOpts={encoding:"utf-8",cwd:workingDir,timeout:options?.timeout,maxBuffer:options?.maxBuffer,stdio:["ignore","pipe","pipe"]};child_process13.execFile("git",args2,execOpts,(error93,output,_stderr)=>{if(error93){reject2(error93);return}resolve101(output??"")})})}catch(err){if(isGitBinaryMissing(err))throw new GitBinaryMissingError("git binary is not available",{cause:err});throw err}}var diff_summary=createSwarmTool({description:"Generate a filtered semantic diff summary from AST analysis. Returns SemanticDiffSummary with optional filtering by classification or riskLevel.",args:{files:exports_external.array(exports_external.string()).describe("Array of file paths to analyze"),classification:exports_external.string().optional().describe("Filter results to only this ChangeCategory"),riskLevel:exports_external.string().optional().describe("Filter results to only this RiskLevel")},async execute(args2,directory,_ctx){let typedArgs=args2;try{if(!typedArgs.files||!Array.isArray(typedArgs.files)||typedArgs.files.length===0)return JSON.stringify({error:"files must be a non-empty array of file paths",success:!1},null,2);let resolved=resolveWorkingDirectory(void 0,directory);if(!resolved.success)return JSON.stringify({success:!1,error:resolved.message},null,2);let workingDir=resolved.directory,astDiffs=[];for(let filePath of typedArgs.files){let astResult=null,fileExistsInHead=!1;try{await execGit2(workingDir,["cat-file","-e",`HEAD:${filePath}`],{timeout:3000}),fileExistsInHead=!0}catch(e){if(e instanceof GitBinaryMissingError)throw e}try{let oldContent,newContent=await fs144.promises.readFile(path255.join(workingDir,filePath),"utf-8");if(fileExistsInHead)oldContent=await execGit2(workingDir,["show",`HEAD:${filePath}`],{timeout:5000,maxBuffer:5242880});else oldContent="";astResult=await computeASTDiff(filePath,oldContent,newContent)}catch(e){if(e instanceof GitBinaryMissingError)throw e;astResult=null}if(astResult&&(astResult.changes.length>0||astResult.error!==void 0))astDiffs.push(astResult)}let filteredChanges=classifyChanges(astDiffs);if(typedArgs.classification)filteredChanges=filteredChanges.filter((change)=>change.category===typedArgs.classification);if(typedArgs.riskLevel)filteredChanges=filteredChanges.filter((change)=>change.riskLevel===typedArgs.riskLevel);let summary=generateSummary(filteredChanges);return JSON.stringify(summary,null,2)}catch(e){let errorResult={error:e instanceof Error?`diff_summary failed: ${e.message}`:"diff_summary failed: unknown error",success:!1};return JSON.stringify(errorResult,null,2)}}});init_p_limit();init_zod();init_candidate_contract();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_gate();import{createHash as createHash47}from"node:crypto";init_p_limit();function createParallelDispatcher(config3){let limit=pLimit(config3.maxConcurrentTasks),activeSlots=new Map,slotCounter=0,shutdownCalled=!1;return{config:config3,dispatch(taskId){if(!config3.enabled)return{action:"reject",reason:"dispatcher_disabled"};if(shutdownCalled)return{action:"reject",reason:"dispatcher_shutdown"};if(activeSlots.size>=config3.maxConcurrentTasks)return{action:"defer",reason:"max_concurrent_tasks_reached"};let slotId=`slot-${++slotCounter}`,runId=`run-${taskId}-${slotId}`,slot={slotId,taskId,runId,startedAt:Date.now()};return activeSlots.set(slotId,slot),limit(async()=>{}),{action:"dispatch",reason:"slot_available",slot}},handles(){return[...activeSlots.values()].map((slot)=>({slotId:slot.slotId,taskId:slot.taskId,runId:slot.runId,cancel:()=>{activeSlots.delete(slot.slotId)}}))},releaseSlot(slotId){activeSlots.delete(slotId)},shutdown(){shutdownCalled=!0,activeSlots.clear(),limit.clearQueue()}}}init_state2();init_ephemeral_session_teardown();init_logger();init_create_tool();var MAX_LANES=8,MAX_PROMPT_CHARS=80000,COMMON_PROMPT_SEPARATOR=`
6368
6355
 
6369
- `,DEFAULT_TIMEOUT_MS5=300000,DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS=30000,MAX_TIMEOUT_MS4=1800000,MAX_LANE_OUTPUT_CHARS=20000,ASYNC_MESSAGE_FETCH_LIMIT=50,MAX_ERROR_CHARS=200,ERROR_TRUNCATION_SUFFIX="...",MAX_BATCH_ID_CHARS=120,DEFAULT_ASYNC_STALE_TIMEOUT_MS=1800000,DEFAULT_COLLECT_TIMEOUT_MS=DEFAULT_ASYNC_STALE_TIMEOUT_MS,MAX_COLLECT_TIMEOUT_MS=3600000,COLLECT_POLL_INTERVAL_MS=500,MAX_COLLECT_POLL_INTERVAL_MS=1e4,MAX_ZOD_ISSUES_LISTED=20,MAX_SESSION_CREATE_GENERATIONS=2,MAX_CREATE_FAILURE_WALK_NODES=64,MAX_CREATE_FAILURE_WALK_DEPTH=6,MAX_CREATE_FAILURE_SIGNAL_CHARS=8192,TRANSIENT_CREATE_STATUS_CODES=new Set([408,429,500,502,503,504,529]),TRANSIENT_CREATE_SIGNAL_PATTERN=/\b(?:408|429|500|502|503|504|529)\b|rate.?limit|timeout|timed.?out|overloaded|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(?:refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,PERMANENT_CREATE_SIGNAL_PATTERN=/authentication|unauthori[sz]ed|forbidden|invalid[_\s-]?(?:api[_\s-]?key|token|credential|configuration|config|agent|model)|unknown[_\s-]?(?:agent|model)|unsupported[_\s-]?(?:agent|model)|model.?not.?found|agent.?not.?found|permission.?denied|access.?denied|quota|usage.?limit|insufficient.?(?:quota|credits?)|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,PERMANENT_CREATE_STATUS_CODES=new Set([400,401,402,403,404,405,409,410,413,422]),CREATE_FAILURE_FIELD_KEYS=["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","message","detail","reason","cause","error","response","data","body","details","errors","isRetryable","retryable"],CREATE_FAILURE_SCALAR_KEYS=new Set(CREATE_FAILURE_FIELD_KEYS),CREATE_FAILURE_STATUS_KEYS=new Set(["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","response"]),AGENT_NAME_SEPARATORS=["_","-"," "],MAX_TRACKED_DELIVERED_LANE_OUTPUTS=1024,deliveredLaneOutputs=new Set;function evictDeliveredLaneOutputsIfOverBound(){while(deliveredLaneOutputs.size>MAX_TRACKED_DELIVERED_LANE_OUTPUTS){let oldestKey=deliveredLaneOutputs.values().next().value;if(oldestKey===void 0)break;deliveredLaneOutputs.delete(oldestKey)}}function boundZodIssues(issues){let formatted=issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`);if(formatted.length<=MAX_ZOD_ISSUES_LISTED)return formatted;let shown=formatted.slice(0,MAX_ZOD_ISSUES_LISTED);return shown.push(`... and ${formatted.length-MAX_ZOD_ISSUES_LISTED} more`),shown}var PR_WORKFLOW_LANE_CHECKLISTS={"intent-architecture":"obligations, claimed versus actual behavior, design fit, callers, consumers, sibling patterns, and documentation","correctness-state":"control flow, boundary conditions, error paths, invariants, state transitions, persistence, and rollback behavior","tests-falsifiability":"assertion strength, negative paths, fixtures and mocks, isolation, CI behavior, and falsification probes","security-trust":"authentication, authorization, untrusted inputs, secrets, injection sinks, privilege, and write authority","reliability-performance":"timeouts, retries, concurrency, cleanup, resource bounds, failure recovery, and performance regressions","compatibility-delivery":"public contracts, schemas, migrations, platform portability, dependencies, packaging, deployment, and release behavior","auth-identity-secrets":"identity, session, permission, authentication, authorization, secret, and cryptographic boundaries","untrusted-input-boundaries":"parsing, serialization, query, template, filesystem, and network sources through every reachable sink","subprocess-platform":"array-form execution, cwd, stdin, timeout, output bounds, kill paths, quoting, and OS/runtime portability","concurrency-state":"locks, queues, caches, transactions, retries, races, session isolation, eviction, and state-machine transitions","dependencies-build-release":"manifests, lockfiles, installers, build scripts, CI, artifacts, provenance, packaging, deployment, and release hygiene","api-schema-migrations":"public APIs, wire/config/storage schemas, compatibility, defaults, migrations, flags, and rollback paths","test-infrastructure":"test validity, isolation, mock leakage, fixtures, harnesses, coverage claims, and CI matrices","ui-accessibility-i18n":"user interaction, rendering, keyboard and screen-reader access, focus, localization, and error states","privacy-observability":"logs, telemetry, analytics, traces, diagnostics, retention, redaction, and sensitive-data exposure","generated-provenance":"generated, vendored, binary, model-produced, codegen, and checked-in artifact source and reproducibility","unclassified-risk":"every changed artifact or behavior not fully covered by another lane, with conservative escalation of ambiguity","stage-b-reviewer":"every feedback item against the exact diff, fix correctness, adjacent regressions, repository contracts, and evidence quality","stage-b-test":"every feedback item with independent targeted negative-path and regression probes on the Stage-A-bound revision","closeout-reviewer":"the complete feedback inventory, final diff, tests, docs, release artifacts, scope, and unresolved risk","closeout-critic":"challenge the closeout evidence, omissions, false confidence, severity, scope, and publication readiness"},EXPLORER_CANDIDATE_FORMAT_SUFFIX=`
6356
+ `,DEFAULT_TIMEOUT_MS5=300000,DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS=30000,MAX_TIMEOUT_MS4=1800000,MAX_LANE_OUTPUT_CHARS=20000,ASYNC_MESSAGE_FETCH_LIMIT=50,MAX_ERROR_CHARS=200,ERROR_TRUNCATION_SUFFIX="...",MAX_BATCH_ID_CHARS=120,DEFAULT_ASYNC_STALE_TIMEOUT_MS=1800000,DEFAULT_COLLECT_TIMEOUT_MS=DEFAULT_ASYNC_STALE_TIMEOUT_MS,MAX_COLLECT_TIMEOUT_MS=3600000,COLLECT_POLL_INTERVAL_MS=500,MAX_COLLECT_POLL_INTERVAL_MS=1e4,MAX_ZOD_ISSUES_LISTED=20,MAX_SESSION_CREATE_GENERATIONS=2,MAX_CREATE_FAILURE_WALK_NODES=64,MAX_CREATE_FAILURE_WALK_DEPTH=6,MAX_CREATE_FAILURE_SIGNAL_CHARS=8192,TRANSIENT_CREATE_STATUS_CODES=new Set([408,429,500,502,503,504,529]),TRANSIENT_CREATE_SIGNAL_PATTERN=/\b(?:408|429|500|502|503|504|529)\b|rate.?limit|timeout|timed.?out|overloaded|temporarily.?unavailable|provider[_\s-]?unavailable|server.?error|network.?connection.?lost|connection.?(?:refused|reset|timeout|lost)|bad.?gateway|gateway.?timeout|internal.?server.?error|service.?unavailable|ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|broken.?pipe|dns(?:[\s_-]+(?:resolution)?)?[\s_-]+fail|name.?not.?resolved|EAI_AGAIN/i,PERMANENT_CREATE_SIGNAL_PATTERN=/authentication|unauthori[sz]ed|forbidden|invalid[_\s-]?(?:api[_\s-]?key|token|credential|configuration|config|agent|model)|unknown[_\s-]?(?:agent|model)|unsupported[_\s-]?(?:agent|model)|model.?not.?found|agent.?not.?found|permission.?denied|access.?denied|quota|usage.?limit|insufficient.?(?:quota|credits?)|payment.?required|credit.?balance|out of credits|billing.?(?:hard.?)?limit/i,PERMANENT_CREATE_STATUS_CODES=new Set([400,401,402,403,404,405,409,410,413,422]),CREATE_FAILURE_FIELD_KEYS=["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","message","detail","reason","cause","error","response","data","body","details","errors","isRetryable","retryable"],CREATE_FAILURE_SCALAR_KEYS=new Set(CREATE_FAILURE_FIELD_KEYS),CREATE_FAILURE_STATUS_KEYS=new Set(["status","statusCode","status_code","httpStatus","http_status","code","errorCode","error_code","response"]),AGENT_NAME_SEPARATORS=["_","-"," "],MAX_TRACKED_DELIVERED_LANE_OUTPUTS=1024,deliveredLaneOutputs=new Set;function evictDeliveredLaneOutputsIfOverBound(){while(deliveredLaneOutputs.size>MAX_TRACKED_DELIVERED_LANE_OUTPUTS){let oldestKey=deliveredLaneOutputs.values().next().value;if(oldestKey===void 0)break;deliveredLaneOutputs.delete(oldestKey)}}function boundZodIssues(issues){let formatted=issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`);if(formatted.length<=MAX_ZOD_ISSUES_LISTED)return formatted;let shown=formatted.slice(0,MAX_ZOD_ISSUES_LISTED);return shown.push(`... and ${formatted.length-MAX_ZOD_ISSUES_LISTED} more`),shown}var PR_WORKFLOW_LANE_CHECKLISTS={"intent-architecture":"obligations, claimed versus actual behavior, design fit, callers, consumers, sibling patterns, and documentation","correctness-state":"control flow, boundary conditions, error paths, invariants, state transitions, persistence, and rollback behavior","tests-falsifiability":"assertion strength, negative paths, fixtures and mocks, isolation, CI behavior, and falsification probes","security-trust":"authentication, authorization, untrusted inputs, secrets, injection sinks, privilege, and write authority","reliability-performance":"timeouts, retries, concurrency, cleanup, resource bounds, failure recovery, and performance regressions","compatibility-delivery":"public contracts, schemas, migrations, platform portability, dependencies, packaging, deployment, and release behavior","auth-identity-secrets":"identity, session, permission, authentication, authorization, secret, and cryptographic boundaries","untrusted-input-boundaries":"parsing, serialization, query, template, filesystem, and network sources through every reachable sink","subprocess-platform":"array-form execution, cwd, stdin, timeout, output bounds, kill paths, quoting, and OS/runtime portability","concurrency-state":"locks, queues, caches, transactions, retries, races, session isolation, eviction, and state-machine transitions","dependencies-build-release":"manifests, lockfiles, installers, build scripts, CI, artifacts, provenance, packaging, deployment, and release hygiene","api-schema-migrations":"public APIs, wire/config/storage schemas, compatibility, defaults, migrations, flags, and rollback paths","test-infrastructure":"test validity, isolation, mock leakage, fixtures, harnesses, coverage claims, and CI matrices","ui-accessibility-i18n":"user interaction, rendering, keyboard and screen-reader access, focus, localization, and error states","privacy-observability":"logs, telemetry, analytics, traces, diagnostics, retention, redaction, and sensitive-data exposure","generated-provenance":"generated, vendored, binary, model-produced, codegen, and checked-in artifact source and reproducibility","unclassified-risk":"every changed artifact or behavior not fully covered by another lane, with conservative escalation of ambiguity","stage-b-reviewer":"every feedback item against the exact diff, fix correctness, adjacent regressions, repository contracts, and evidence quality","stage-b-test":"every feedback item with independent targeted negative-path and regression probes on the Stage-A-bound revision","closeout-reviewer":"the complete feedback inventory, final diff, tests, docs, release artifacts, scope, and unresolved risk","closeout-critic":"challenge the closeout evidence, omissions, false confidence, severity, scope, and publication readiness"},EXPLORER_CANDIDATE_COMMON_RULES=`
6370
6357
 
6371
6358
  IMPORTANT — OUTPUT FORMAT REQUIREMENT:
6372
- You MUST emit your findings as a pipe-delimited [CANDIDATE] table. The FIRST
6373
- [CANDIDATE]-prefixed line is the literal column header, copied verbatim with the
6374
- field NAMES as its values; data rows follow it.
6359
+ You MUST emit findings as a pipe-delimited [CANDIDATE] table. The FIRST
6360
+ [CANDIDATE]-prefixed line is the literal column header shown below, copied
6361
+ verbatim with field NAMES as its values; data rows follow it.
6375
6362
 
6376
- WORKED EXAMPLE copy this shape exactly. The first line is the header, not a finding:
6377
- ${CANDIDATE_HEADERS.base_explorer}
6378
- [CANDIDATE] | example-lane-001 | example-lane | MEDIUM | correctness | src/a.ts:12 | claim without pipes | evidence without pipes | impact without pipes | HIGH
6363
+ Every candidate data row has exactly ${CANDIDATE_FIELD_COUNT} fields after the
6364
+ marker. A literal pipe inside any field MUST be written as \\| — an unescaped |
6365
+ starts a new field, and the row is rejected as malformed. The confidence value
6366
+ is the final data field and must be exactly one token: HIGH, MEDIUM, or LOW.
6367
+
6368
+ Candidate IDs must be globally unique across the run; prefix them with the
6369
+ exact workflow_lane value from this dispatch. Emit the header and machine rows
6370
+ as plain text, never inside Markdown code fences; fenced rows are ignored as
6371
+ quoted or example material.`,EXPLORER_CANDIDATE_COMMON_END=`
6372
+ A [CLEAN] row has exactly ${CLEAN_FIELD_COUNT-1} fields after the marker and NO
6373
+ confidence field or trailing field. Emit it ONLY when the lane has zero findings
6374
+ — never alongside [CANDIDATE] rows. Write a substantive coverage_scope of at least 12
6375
+ characters and concrete evidence of at least 20 characters; bare
6376
+ header-only output is UNATTESTED for every PR-review lane.
6377
+ Do NOT use the default PROJECT/STRUCTURE output format for this dispatch.`,BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX=`${EXPLORER_CANDIDATE_COMMON_RULES}
6379
6378
 
6380
- Standard explorer format (use unless the prompt specifies micro-lane work):
6379
+ BASE WORKED EXAMPLE copy only this shape. The first line is the header, not a finding:
6381
6380
  ${CANDIDATE_HEADERS.base_explorer}
6381
+ [CANDIDATE] | example-base-001 | example-base | MEDIUM | correctness | src/a.ts:12 | claim without pipes | evidence without pipes | impact without pipes | HIGH
6382
+
6383
+ If this base explorer finds zero issues, emit its header followed by exactly:
6384
+ ${CLEAN_TEMPLATES.base_explorer}
6385
+ ${EXPLORER_CANDIDATE_COMMON_END}`,MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX=`${EXPLORER_CANDIDATE_COMMON_RULES}
6382
6386
 
6383
- Micro-lane format (use when the prompt references invariant checking or micro_lane, or for swarm-pr-review:council discovery):
6387
+ MICRO WORKED EXAMPLE copy only this shape. The first line is the header, not a finding:
6384
6388
  ${CANDIDATE_HEADERS.micro_lane}
6389
+ [CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
6385
6390
 
6386
- Every data row has exactly ${CANDIDATE_FIELD_COUNT} fields after the marker. A
6387
- literal pipe inside any field MUST be written as \\| — an unescaped | starts a
6388
- new field, and the row is then rejected as malformed.
6391
+ If this micro or council explorer finds zero issues, emit its header followed by exactly:
6392
+ ${CLEAN_TEMPLATES.micro_lane}
6393
+ ${EXPLORER_CANDIDATE_COMMON_END}`,EXPLORER_CANDIDATE_FORMAT_SUFFIX=`${EXPLORER_CANDIDATE_COMMON_RULES}
6389
6394
 
6390
- Candidate IDs must be globally unique across the run; prefix them with the
6391
- exact workflow_lane value from this dispatch.
6395
+ Choose exactly one family from the dispatch context. Never combine fields from
6396
+ the two families.
6392
6397
 
6393
- If a standard explorer finds zero issues, emit its header followed by exactly:
6394
- ${CLEAN_TEMPLATES.base_explorer}
6395
- If a micro-lane finds zero issues, emit its header followed by exactly:
6396
- ${CLEAN_TEMPLATES.micro_lane}
6397
- A [CLEAN] row has exactly ${CLEAN_FIELD_COUNT-1} fields after the marker and NO
6398
- confidence field. Emit it ONLY when the lane has zero findings — never alongside
6399
- [CANDIDATE] rows.
6400
- Write a substantive coverage_scope of at least 12 characters and concrete evidence of at least 20
6401
- characters; bare header-only output is UNATTESTED for every PR-review lane.
6402
- Do NOT use the default PROJECT/STRUCTURE output format for this dispatch.`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Exact repository-agnostic trigger ledger required for swarm-pr-review:micro; MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED"),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals179={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals179.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals179.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals179.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals179.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals179.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals179.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form, then verify with: git -C "${directory}" fetch origin <base-branch> && git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M)")}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);validatePrReviewMicroDispatch(parsed.data,depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,parsed.data.trigger_evaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals179.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals179.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals179.now()+timeoutMs,hostTimeouts=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals179.now()>=deadline){keepPolling=!1;continue}await _internals179.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals179.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0);if(hostTimeouts.size>0)result.message="Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let collectedRevisionDigest=record3.workspace?.prHeadSha?await _internals179.resolvePrWorkflowRevisionDigestAsync(directory,record3.workspace.prHeadSha)??void 0:void 0,output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length)prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged];if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId,deadline,hostTimeouts){if(typeof session.status!=="function")return!0;try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts);if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now=_internals179.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6398
+ BASE WORKED EXAMPLE:
6399
+ ${CANDIDATE_HEADERS.base_explorer}
6400
+ [CANDIDATE] | example-base-001 | example-base | MEDIUM | correctness | src/a.ts:12 | claim without pipes | evidence without pipes | impact without pipes | HIGH
6401
+ Zero findings: ${CLEAN_TEMPLATES.base_explorer}
6402
+
6403
+ MICRO WORKED EXAMPLE:
6404
+ ${CANDIDATE_HEADERS.micro_lane}
6405
+ [CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
6406
+ Zero findings: ${CLEAN_TEMPLATES.micro_lane}
6407
+ ${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals179={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals179.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals179.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals179.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals179.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals179.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals179.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form, then verify with: git -C "${directory}" fetch origin <base-branch> && git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M)")}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals179.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals179.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals179.now()+timeoutMs,hostTimeouts=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals179.now()>=deadline){keepPolling=!1;continue}await _internals179.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals179.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0);if(hostTimeouts.size>0)result.message="Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let collectedRevisionDigest=record3.workspace?.prHeadSha?await _internals179.resolvePrWorkflowRevisionDigestAsync(directory,record3.workspace.prHeadSha)??void 0:void 0,output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length)prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged];if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId,deadline,hostTimeouts){if(typeof session.status!=="function")return!0;try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts);if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now=_internals179.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6403
6408
 
6404
- `),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0;try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let promptResult=await withTimeout2(session.prompt({path:{id:sessionId},body:{agent:lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${timeoutMs}ms`,promptController);if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)});return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){return failedLane(lane,role,startedAt,formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed");return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults}}function recordToLaneResult(record3,batchId){let status=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"||record3.status==="ingesting"?"pending":record3.status,laneId=record3.laneId??record3.correlationId,digest3=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1;if(record3.result?.text!==void 0&&status!=="pending"&&digest3&&outputRef){let key=`${batchId}\x00${laneId}\x00${digest3}`;if(alreadyDelivered=deliveredLaneOutputs.has(key),!alreadyDelivered)deliveredLaneOutputs.add(key),evictDeliveredLaneOutputsIfOverBound()}return{id:laneId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status,session_id:record3.subagentSessionId,generation:record3.generation??1,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{...alreadyDelivered?{output_omitted_repeat:!0}:{output:record3.result.text},output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId,generation){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,generation,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals179.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;return tools.write=!1,tools.edit=!1,tools.patch=!1,tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult2(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes,options={}){let generatedAgentNames=_internals179.getGeneratedAgentNames(),errors5=[],formatted=lanes.map((lane)=>{let role=resolveGeneratedAgentRole(lane.agent,generatedAgentNames),isPrReviewCouncilExplorer=options.mode==="swarm-pr-review:council"&&role.startsWith("council_");if(role!=="explorer"&&!isPrReviewCouncilExplorer)return lane;if(lane.prompt.endsWith(EXPLORER_CANDIDATE_FORMAT_SUFFIX))return lane;let rowFamilyIdentity=options.mode==="swarm-pr-review:base"?"For this base explorer lane, use the base row family and put the exact workflow_lane only in the `lane` field.":options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?"For this micro/council lane, use the micro row family and put the exact workflow_lane only in the `micro_lane` field; do not use the base `lane` field.":"Use the row family applicable to this dispatch and put the exact workflow_lane only in that family's `lane` or `micro_lane` field.",exactLane=lane.workflow_lane??lane.id,ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:[exactLane],identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,prompt=`${lane.prompt}
6409
+ `),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0;try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let promptResult=await withTimeout2(session.prompt({path:{id:sessionId},body:{agent:lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${timeoutMs}ms`,promptController);if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)});return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){return failedLane(lane,role,startedAt,formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed");return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults}}function recordToLaneResult(record3,batchId){let status=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"||record3.status==="ingesting"?"pending":record3.status,laneId=record3.laneId??record3.correlationId,digest3=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1;if(record3.result?.text!==void 0&&status!=="pending"&&digest3&&outputRef){let key=`${batchId}\x00${laneId}\x00${digest3}`;if(alreadyDelivered=deliveredLaneOutputs.has(key),!alreadyDelivered)deliveredLaneOutputs.add(key),evictDeliveredLaneOutputsIfOverBound()}return{id:laneId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status,session_id:record3.subagentSessionId,generation:record3.generation??1,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{...alreadyDelivered?{output_omitted_repeat:!0}:{output:record3.result.text},output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId,generation){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,generation,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals179.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;return tools.write=!1,tools.edit=!1,tools.patch=!1,tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult2(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes,options={}){let generatedAgentNames=_internals179.getGeneratedAgentNames(),errors5=[],formatted=lanes.map((lane)=>{let role=resolveGeneratedAgentRole(lane.agent,generatedAgentNames),isPrReviewCouncilExplorer=options.mode==="swarm-pr-review:council"&&role.startsWith("council_");if(role!=="explorer"&&!isPrReviewCouncilExplorer)return lane;let rowFamilyIdentity=options.mode==="swarm-pr-review:base"?"For this base explorer lane, use the base row family and put the exact workflow_lane only in the `lane` field.":options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?"For this micro/council lane, use the micro row family and put the exact workflow_lane only in the `micro_lane` field; do not use the base `lane` field.":"Use the row family applicable to this dispatch and put the exact workflow_lane only in that family's `lane` or `micro_lane` field.",exactLane=lane.workflow_lane??lane.id,ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:[exactLane],identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,formatSuffix=options.mode==="swarm-pr-review:base"?BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX:options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX:EXPLORER_CANDIDATE_FORMAT_SUFFIX,controllerIdentity=`CONTROLLER-BOUND OUTPUT IDENTITY: ${identity}. Placeholder text such as "workflow_lane" is invalid. ${rowFamilyIdentity}`,embeddedKnownSuffixes=[EXPLORER_CANDIDATE_FORMAT_SUFFIX,BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX,MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX].filter((suffix)=>lane.prompt.includes(suffix)),expectedSuffixOccurrences=lane.prompt.split(formatSuffix).length-1;if(lane.prompt.endsWith(formatSuffix)&&lane.prompt.includes(controllerIdentity)&&embeddedKnownSuffixes.length===1&&expectedSuffixOccurrences===1)return lane;if(embeddedKnownSuffixes.length>0){let diagnostic=`Lane "${lane.id}" prompt contains an incompatible, duplicate, or controller-unbound explorer output contract for mode "${options.mode??"generic"}"`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let prompt=`${lane.prompt}
6405
6410
 
6406
- CONTROLLER-BOUND OUTPUT IDENTITY: ${identity}. Placeholder text such as "workflow_lane" is invalid. ${rowFamilyIdentity}${EXPLORER_CANDIDATE_FORMAT_SUFFIX}`;if(prompt.length>MAX_PROMPT_CHARS){let diagnostic=`Lane "${lane.id}" prompt plus mandatory explorer output contract is ${prompt.length} chars; max ${MAX_PROMPT_CHARS}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: lane "${lane.id}" prompt too long (${lane.prompt.length} chars + suffix = ${prompt.length}, max ${MAX_PROMPT_CHARS}); `+"format enforcement skipped — explorer may not emit [CANDIDATE] rows"),lane}return{...lane,prompt}});return errors5.length>0?{ok:!1,errors:errors5}:{ok:!0,lanes:formatted}}function applyPrWorkflowPromptContract(lanes,options){let mode=options.mode;if(!mode?.startsWith("swarm-pr-review:")&&!mode?.startsWith("swarm-pr-feedback:"))return{ok:!0,lanes:[...lanes]};if(!options.prHeadSha||!options.revisionDigest)return{ok:!1,errors:["PR workflow prompts require controller-verified head and revision bindings"]};let errors5=[],contracted=lanes.map((lane)=>{let workflowLane=lane.workflow_lane??"",assignedIds=lane.review_item_ids??lane.feedback_item_ids??[],fallbackChecklist=mode.endsWith(":reviewer")?"re-read every assigned candidate at its exact location; prove classification, reachability, mitigation, severity, and falsification path":mode.endsWith(":critic")?"challenge every assigned verdict for evidence, reachability, mitigation, severity, coherence, and required report changes":"inspect the bound scope using the complete repository-defined contract for this lane",ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:void 0,checklist=ownedLanes?ownedLanes.map((owned)=>`[${owned}] ${PR_WORKFLOW_LANE_CHECKLISTS[owned]??fallbackChecklist}`).join(" "):PR_WORKFLOW_LANE_CHECKLISTS[workflowLane]??fallbackChecklist,ownedLine=ownedLanes?`
6411
+ ${controllerIdentity}${formatSuffix}`;if(prompt.length>MAX_PROMPT_CHARS){let diagnostic=`Lane "${lane.id}" prompt plus mandatory explorer output contract is ${prompt.length} chars; max ${MAX_PROMPT_CHARS}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: lane "${lane.id}" prompt too long (${lane.prompt.length} chars + suffix = ${prompt.length}, max ${MAX_PROMPT_CHARS}); `+"format enforcement skipped — explorer may not emit [CANDIDATE] rows"),lane}return{...lane,prompt}});return errors5.length>0?{ok:!1,errors:errors5}:{ok:!0,lanes:formatted}}function applyPrWorkflowPromptContract(lanes,options){let mode=options.mode;if(!mode?.startsWith("swarm-pr-review:")&&!mode?.startsWith("swarm-pr-feedback:"))return{ok:!0,lanes:[...lanes]};if(!options.prHeadSha||!options.revisionDigest)return{ok:!1,errors:["PR workflow prompts require controller-verified head and revision bindings"]};let errors5=[],contracted=lanes.map((lane)=>{let workflowLane=lane.workflow_lane??"",assignedIds=lane.review_item_ids??lane.feedback_item_ids??[],fallbackChecklist=mode.endsWith(":reviewer")?"re-read every assigned candidate at its exact location; prove classification, reachability, mitigation, severity, and falsification path":mode.endsWith(":critic")?"challenge every assigned verdict for evidence, reachability, mitigation, severity, coherence, and required report changes":"inspect the bound scope using the complete repository-defined contract for this lane",ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:void 0,checklist=ownedLanes?ownedLanes.map((owned)=>`[${owned}] ${PR_WORKFLOW_LANE_CHECKLISTS[owned]??fallbackChecklist}`).join(" "):PR_WORKFLOW_LANE_CHECKLISTS[workflowLane]??fallbackChecklist,ownedLine=ownedLanes?`
6407
6412
  owned_workflow_lanes: ${ownedLanes.join(", ")} — every owned obligation requires its own [CANDIDATE] rows or fully populated [CLEAN] attestation naming that obligation`:"",contract=`
6408
6413
 
6409
6414
  [CONTROLLER-BOUND PR WORKFLOW CONTRACT]
@@ -6577,7 +6582,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
6577
6582
  `).replace(/\n{3,}/g,`
6578
6583
 
6579
6584
  `).trim()}function makeAbortError(){try{return new DOMException("The operation was aborted","AbortError")}catch{let err2=Error("The operation was aborted");return err2.name="AbortError",err2}}function performHttpRequest(args2){let{url:url3,pinnedAddress,signal:signal2,headers}=args2,isHttps=url3.protocol==="https:",port=url3.port?Number(url3.port):isHttps?443:80,hostNoBrackets=url3.hostname.replace(/^\[|\]$/g,""),useSni=isHttps&&isIP(hostNoBrackets)===0,options={host:pinnedAddress,port,path:`${url3.pathname}${url3.search}`,method:"GET",headers:{Host:url3.host,...headers}};if(useSni)options.servername=url3.hostname;return new Promise((resolve121,reject2)=>{let req,onResponse=(res)=>{let normHeaders={};for(let[key,value]of Object.entries(res.headers))normHeaders[key]=Array.isArray(value)?value[0]:value;res.on("error",()=>{}),resolve121({status:res.statusCode??0,headers:normHeaders,body:res,cancel:()=>req.destroy()})};req=isHttps?https.request(options,onResponse):http.request(options,onResponse);let onAbort=()=>req.destroy(makeAbortError());if(signal2.aborted)req.destroy(makeAbortError());else signal2.addEventListener("abort",onAbort,{once:!0});req.on("error",reject2),req.end()})}async function boundedFetch(start,maxBytes,timeoutMs,deps){let current=start,controller=new AbortController,timer=setTimeout(()=>controller.abort(),timeoutMs);try{for(let hop=0;hop<=MAX_REDIRECTS;hop++){let raw;try{raw=await deps.httpRequest({url:current.url,pinnedAddress:current.address,signal:controller.signal,headers:{Accept:"text/html,application/xhtml+xml,text/plain,application/json;q=0.9,*/*;q=0.5"}})}catch(err2){if(controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms for ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}if(raw.status>=300&&raw.status<400){let location=raw.headers.location;if(raw.cancel?.(),!location)return{ok:!1,reason:"bad_redirect",message:`Redirect ${raw.status} with no Location header.`};let next;try{next=new URL(location,current.url)}catch{return{ok:!1,reason:"bad_redirect",message:`Invalid redirect target: ${location}`}}let revalidated=await validateFetchUrl(next.toString(),deps.dnsLookup);if(!revalidated.ok)return revalidated;if(hop===MAX_REDIRECTS)return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`};current={url:revalidated.url,address:revalidated.address};continue}if(raw.status<200||raw.status>=300)return raw.cancel?.(),{ok:!1,reason:"http_error",message:`HTTP ${raw.status} for ${current.url.toString()}`};let contentType=raw.headers["content-type"]??null;if(!isAllowedContentType(contentType))return raw.cancel?.(),{ok:!1,reason:"unsupported_content_type",message:`Refusing to read non-text content type "${contentType}".`};let activeBody=raw.body;if(raw.body!==null&&raw.body instanceof Readable){let encoding=(raw.headers["content-encoding"]??"").toLowerCase(),decoder=null;if(encoding==="gzip"||encoding==="x-gzip")decoder=raw.body.pipe(zlib.createGunzip());else if(encoding==="deflate")decoder=raw.body.pipe(zlib.createInflate());else if(encoding==="br")decoder=raw.body.pipe(zlib.createBrotliDecompress());if(decoder)decoder.on("error",()=>{}),activeBody=decoder}let body;try{body=await readBounded(activeBody,maxBytes)}catch(err2){if(raw.cancel?.(),controller.signal.aborted)return{ok:!1,reason:"timeout",message:`Fetch exceeded ${timeoutMs}ms while reading the body of ${current.url.toString()}`};return{ok:!1,reason:"network_error",message:err2 instanceof Error?err2.message:String(err2)}}return raw.cancel?.(),{ok:!0,outcome:{status:raw.status,finalUrl:current.url.toString(),contentType,bytes:body.bytes,truncated:body.truncated}}}return{ok:!1,reason:"too_many_redirects",message:`Exceeded ${MAX_REDIRECTS} redirect hops.`}}finally{clearTimeout(timer)}}async function readBounded(body,maxBytes){if(!body)return{bytes:new Uint8Array(0),truncated:!1};let chunks=[],received=0,truncated=!1;for await(let value of body){if(!value||value.byteLength===0)continue;if(chunks.push(value),received+=value.byteLength,received>maxBytes){truncated=!0;break}}let merged=new Uint8Array(Math.min(received,maxBytes)),offset=0;for(let chunk of chunks){if(offset>=merged.length)break;let slice=chunk.subarray(0,merged.length-offset);merged.set(slice,offset),offset+=slice.byteLength}return{bytes:merged,truncated}}var web_fetch=createSwarmTool({description:"Fetch the readable text of a single http(s) URL for architect-driven deep research (MODE: DEEP_RESEARCH). Returns decoded page text (HTML stripped to plain text), the document title, the final URL after redirects, and an evidence reference stored alongside web_search results. Use it to read primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled; no search API key required. Blocks private/loopback/link-local/metadata addresses (re-validated across redirects), enforces a timeout, and caps the response body size.",args:{url:exports_external.string().min(1).max(2048).describe("Absolute http(s) URL to fetch (1–2048 chars)."),max_bytes:exports_external.number().int().min(1024).max(MAX_BYTES_HARD_CAP).optional().describe(`Max decoded response bytes to read (1024..${MAX_BYTES_HARD_CAP}, default ${DEFAULT_MAX_BYTES2}).`),timeout_ms:exports_external.number().int().min(1000).max(MAX_TIMEOUT_MS5).optional().describe(`Request timeout in ms (1000..${MAX_TIMEOUT_MS5}, default ${DEFAULT_TIMEOUT_MS6}).`),working_directory:exports_external.string().optional().describe("Project root for config resolution and evidence storage. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema6.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=_internals215.loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_fetch is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let validated=await validateFetchUrl(parsed.data.url,_internals215.dnsLookup);if(!validated.ok){let fail={success:!1,reason:validated.reason,message:validated.message};return JSON.stringify(fail,null,2)}let maxBytes=parsed.data.max_bytes??DEFAULT_MAX_BYTES2,timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS6,result=await boundedFetch({url:validated.url,address:validated.address},maxBytes,timeoutMs,_internals215);if(!result.ok){let fail={success:!1,reason:result.reason,message:result.message};return JSON.stringify(fail,null,2)}let{outcome}=result,raw=new TextDecoder("utf-8",{fatal:!1}).decode(outcome.bytes),isHtml=(outcome.contentType??"").toLowerCase().includes("html")||/<html|<!doctype html/i.test(raw),title=isHtml?extractTitle(raw):void 0,bodyText=isHtml?htmlToText(raw):raw.replace(/\s*\n\s*/g,`
6580
- `).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals215.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals215={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals216.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals216={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store4();init_create_tool();init_resolve_working_directory();import*as path300 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path300.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs180 from"node:fs";import path301 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals217.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals217.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path301.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path301.dirname(validatedPath);try{await fs180.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path301.join(evidenceDir,`.${filename}.tmp`);return await fs180.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs180.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals217={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();import fs181 from"node:fs";import path302 from"node:path";init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],VerdictSchema3=exports_external.object({agent:exports_external.enum(FINAL_COUNCIL_MEMBERS),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,membersVoted=[...new Set(input.verdicts.map((v)=>v.agent))],membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!membersVoted.includes(member));return runCouncilAttempt({directory,scope:{kind:"final",generation:planHash??"missing-plan"},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<FINAL_COUNCIL_MEMBERS.length)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${FINAL_COUNCIL_MEMBERS.length} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.`,membersVoted,membersAbsent,quorumRequired:FINAL_COUNCIL_MEMBERS.length},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),input.verdicts,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals218.validateSwarmPath(directory,path302.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path302.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path302.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computePlanHash(currentPlan)!==planHash)throw Error("final council plan changed before evidence publication");await fs181.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path302.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs181.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs181.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs181.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer.")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path302.join("evidence","final-council.json")),parsed=JSON.parse(fs181.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals218={validateSwarmPath};init_zod();import fs182 from"node:fs";import path303 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals219.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path303.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path303.dirname(validatedPath);try{await fs182.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path303.join(evidenceDir,`.${filename}.tmp`);return await fs182.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs182.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals219={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs183 from"node:fs";import path304 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals220.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path304.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path304.dirname(validatedPath);try{await fs183.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path304.join(evidenceDir,`.${filename}.tmp`);return await fs183.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs183.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals220={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID26}from"node:crypto";import*as fs184 from"node:fs";import*as path305 from"node:path";var RunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),FindingSchema4=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"]),severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),HandoffSchema=exports_external.object({pr_url:exports_external.string().url(),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),records:exports_external.array(FindingSchema4).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:HandoffSchema}).strict()]);function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{let stat19=await fs184.promises.stat(filePath);if(!stat19.isFile()||stat19.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs184.promises.readFile(filePath,"utf8")).split(/\r?\n/).filter(Boolean).map((line)=>JSON.parse(line))}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function atomicWrite6(filePath,content){await fs184.promises.mkdir(path305.dirname(filePath),{recursive:!0});let tempPath=path305.join(path305.dirname(filePath),`.${path305.basename(filePath)}.${randomUUID26()}.tmp`);try{await fs184.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs184.promises.rename(tempPath,filePath)}finally{await fs184.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3("PR-review artifact requires an active session");let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3("PR-review artifact requires an active, bound PR_REVIEW gate");if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(`PR-review artifact head mismatch: expected ${state.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==parsed.data.run_id)return failure3(`PR-review artifacts are already bound to run ${state.prReviewArtifactRunId}`);let relativeFindingsPath=path305.join("pr-review",parsed.data.run_id,"findings.jsonl"),findingsPath=validateSwarmPath(directory,relativeFindingsPath),existing=await readFindings(findingsPath);if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id);await assertPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,findingIds),await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records);let recordedAt=new Date().toISOString(),appended=findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];await atomicWrite6(findingsPath,allRecords.map((record3)=>JSON.stringify(record3)).join(`
6585
+ `).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals215.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals215={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals216.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals216={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store4();init_create_tool();init_resolve_working_directory();import*as path300 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path300.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs180 from"node:fs";import path301 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals217.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals217.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path301.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path301.dirname(validatedPath);try{await fs180.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path301.join(evidenceDir,`.${filename}.tmp`);return await fs180.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs180.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals217={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();import fs181 from"node:fs";import path302 from"node:path";init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],VerdictSchema3=exports_external.object({agent:exports_external.enum(FINAL_COUNCIL_MEMBERS),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,membersVoted=[...new Set(input.verdicts.map((v)=>v.agent))],membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!membersVoted.includes(member));return runCouncilAttempt({directory,scope:{kind:"final",generation:planHash??"missing-plan"},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<FINAL_COUNCIL_MEMBERS.length)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${FINAL_COUNCIL_MEMBERS.length} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.`,membersVoted,membersAbsent,quorumRequired:FINAL_COUNCIL_MEMBERS.length},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),input.verdicts,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals218.validateSwarmPath(directory,path302.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path302.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path302.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computePlanHash(currentPlan)!==planHash)throw Error("final council plan changed before evidence publication");await fs181.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path302.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs181.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs181.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs181.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer.")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path302.join("evidence","final-council.json")),parsed=JSON.parse(fs181.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals218={validateSwarmPath};init_zod();import fs182 from"node:fs";import path303 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals219.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path303.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path303.dirname(validatedPath);try{await fs182.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path303.join(evidenceDir,`.${filename}.tmp`);return await fs182.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs182.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals219={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs183 from"node:fs";import path304 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals220.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path304.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path304.dirname(validatedPath);try{await fs183.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path304.join(evidenceDir,`.${filename}.tmp`);return await fs183.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs183.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals220={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_candidate_contract();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID26}from"node:crypto";import*as fs184 from"node:fs";import*as path305 from"node:path";var RunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),FindingSchema4=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"]),severity:exports_external.enum(CANDIDATE_SEVERITIES).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),HandoffSchema=exports_external.object({pr_url:exports_external.string().url(),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),records:exports_external.array(FindingSchema4).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:HandoffSchema}).strict()]);function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{let stat19=await fs184.promises.stat(filePath);if(!stat19.isFile()||stat19.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs184.promises.readFile(filePath,"utf8")).split(/\r?\n/).filter(Boolean).map((line)=>JSON.parse(line))}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function atomicWrite6(filePath,content){await fs184.promises.mkdir(path305.dirname(filePath),{recursive:!0});let tempPath=path305.join(path305.dirname(filePath),`.${path305.basename(filePath)}.${randomUUID26()}.tmp`);try{await fs184.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs184.promises.rename(tempPath,filePath)}finally{await fs184.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3("PR-review artifact requires an active session");let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3("PR-review artifact requires an active, bound PR_REVIEW gate");if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(`PR-review artifact head mismatch: expected ${state.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==parsed.data.run_id)return failure3(`PR-review artifacts are already bound to run ${state.prReviewArtifactRunId}`);let relativeFindingsPath=path305.join("pr-review",parsed.data.run_id,"findings.jsonl"),findingsPath=validateSwarmPath(directory,relativeFindingsPath),existing=await readFindings(findingsPath);if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id);await assertPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,findingIds),await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records);let recordedAt=new Date().toISOString(),appended=findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];await atomicWrite6(findingsPath,allRecords.map((record3)=>JSON.stringify(record3)).join(`
6581
6586
  `)+(allRecords.length>0?`
6582
6587
  `:""));let handoffRequired=[...latestFindings(allRecords).values()].some((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback");return await markPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,relativeFindingsPath.split(path305.sep).join("/"),findingIds,handoffRequired),JSON.stringify({success:!0,path:relativeFindingsPath.split(path305.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,handoff_required:handoffRequired},null,2)}let actionableIds=[...latestFindings(existing).values()].filter((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback").map((record3)=>record3.finding_id).sort(),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`handoff finding_ids must exactly match actionable findings: ${actionableIds.join(", ")||"(none)"}`);let relativeHandoffPath=path305.join("pr-review",parsed.data.run_id,"feedback-handoff.json"),handoffPath=validateSwarmPath(directory,relativeHandoffPath);return await atomicWrite6(handoffPath,`${JSON.stringify({schema_version:1,run_id:parsed.data.run_id,pr_head_sha:state.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},null,2)}
6583
6588
  `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path305.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path305.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(FindingSchema4).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID27}from"node:crypto";import fs185 from"node:fs";import path306 from"node:path";var _internals221={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals221.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals221.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals221.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(`PR_REVIEW trigger evaluation head mismatch: expected ${gateState.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(gateState.prReviewArtifactRunId&&gateState.prReviewArtifactRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation run_id must match the findings artifact run "${gateState.prReviewArtifactRunId}"`);if(gateState.prReviewTriggerEvalRunId&&gateState.prReviewTriggerEvalRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation is already bound to run "${gateState.prReviewTriggerEvalRunId}"`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigest(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4("Active PR_REVIEW trigger evaluation could not bind the current exact revision digest");let citedLaneOwnership=new Map;for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||record3.status!=="completed"||record3.result?.outputDegraded===!0||record3.result?.transcriptIncomplete===!0||record3.result?.truncated===!0||(record3.result?.chars??0)<=0||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||!recordOwnedLanes.every((ownedFamily)=>prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,ownedFamily,recordOwnedLanes,record3.mode))||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a completed non-degraded micro-lane artifact`)}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");let resolvedMergeBase=_internals221.resolveMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedMergeBase)return failure4("Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref and pr_head_sha");if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let artifact=buildPrReviewTriggerReceiptV2({run_id:parsed.data.run_id,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows}),relativePath2=path306.join("pr-review",parsed.data.run_id,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(fs185.existsSync(destination))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${parsed.data.run_id}" and cannot be overwritten; abort the workflow with abort_pr_workflow to restart`);let parent=path306.dirname(destination),tempPath=path306.join(parent,`.trigger-eval.${randomUUID27()}.tmp`);try{await fs185.promises.mkdir(parent,{recursive:!0}),await fs185.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}