opencode-swarm 7.172.1 → 7.172.2

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 (58) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{coder-settlement-pw4jbrez.js → coder-settlement-trba7st8.js} +4 -4
  4. package/dist/cli/{config-doctor-ab0ckcsc.js → config-doctor-229ewr8f.js} +3 -3
  5. package/dist/cli/{core-ty98bsnz.js → core-2ytpkhxc.js} +2 -2
  6. package/dist/cli/{curator-llm-factory-69vje2m7.js → curator-llm-factory-8evp80zs.js} +20 -20
  7. package/dist/cli/{curator-rvrhbsy2.js → curator-qfwgj2y7.js} +20 -20
  8. package/dist/cli/{evidence-summary-service-wmer0c5b.js → evidence-summary-service-5t5vr9w9.js} +7 -7
  9. package/dist/cli/{gate-evidence-6d0f6ekr.js → gate-evidence-27j4pm1v.js} +3 -3
  10. package/dist/cli/{guardrail-explain-z06dyan0.js → guardrail-explain-65zzxh0c.js} +21 -21
  11. package/dist/cli/{guardrail-log-bmyxcdfk.js → guardrail-log-0y9xmnpd.js} +4 -4
  12. package/dist/cli/{guardrail-reset-9wmbhwff.js → guardrail-reset-f5d89j15.js} +20 -20
  13. package/dist/cli/{hive-promoter-mc8xssba.js → hive-promoter-66bhdee6.js} +20 -20
  14. package/dist/cli/{index-zcjdw8dw.js → index-0tmrdj9m.js} +1 -1
  15. package/dist/cli/{index-c5wyannc.js → index-27k76kef.js} +2 -2
  16. package/dist/cli/{index-y21gyrt6.js → index-3d3h79cj.js} +22 -22
  17. package/dist/cli/{index-jc0as97z.js → index-3vscksqk.js} +1 -1
  18. package/dist/cli/{index-br08k19k.js → index-4xszpb54.js} +54 -54
  19. package/dist/cli/{index-hx0pas8b.js → index-5z71h1j4.js} +2 -2
  20. package/dist/cli/{index-re1ey51s.js → index-93b6dm58.js} +3 -3
  21. package/dist/cli/{index-sakgsnxj.js → index-aa0yaw9b.js} +2 -2
  22. package/dist/cli/{index-twpzfwga.js → index-byf75cte.js} +2 -2
  23. package/dist/cli/{index-pmg1k4mv.js → index-d1nb8eb3.js} +3 -3
  24. package/dist/cli/{index-3r17j2gc.js → index-d8mbaj41.js} +3 -3
  25. package/dist/cli/{index-ecaws78e.js → index-depxc452.js} +1 -1
  26. package/dist/cli/{index-66tshqdp.js → index-etjq0r06.js} +1 -1
  27. package/dist/cli/{index-vqs7dxp7.js → index-fck5xq4y.js} +4 -4
  28. package/dist/cli/{index-q58xegd7.js → index-fgzh858k.js} +2 -2
  29. package/dist/cli/{index-dg5znyqw.js → index-mfjep91k.js} +1 -1
  30. package/dist/cli/{index-j8warkkj.js → index-mq1z10v1.js} +4 -4
  31. package/dist/cli/{index-008sppht.js → index-p5fdk20g.js} +2 -2
  32. package/dist/cli/{index-tm6z0wgj.js → index-pre6sqz8.js} +1 -1
  33. package/dist/cli/{index-wf6pbrg7.js → index-t7yn457b.js} +1 -1
  34. package/dist/cli/{index-93z2fhyp.js → index-vbgpxbmm.js} +3 -3
  35. package/dist/cli/{index-rhe9zbe2.js → index-wk58ymh3.js} +20 -20
  36. package/dist/cli/{index-edext37b.js → index-wpcwwf61.js} +2 -2
  37. package/dist/cli/{index-w0141tkw.js → index-ybwtp7n4.js} +3 -3
  38. package/dist/cli/{index-qfz31dcy.js → index-yxptsaea.js} +5 -5
  39. package/dist/cli/index.js +21 -21
  40. package/dist/cli/{knowledge-escalator-k4ab3f1f.js → knowledge-escalator-f5d966wd.js} +7 -7
  41. package/dist/cli/{knowledge-events-aqy4hb15.js → knowledge-events-9ye18tpn.js} +5 -5
  42. package/dist/cli/{knowledge-store-xgkga9xj.js → knowledge-store-g8ge5m6j.js} +1 -1
  43. package/dist/cli/{knowledge-validator-vvgs8m7m.js → knowledge-validator-r2hdm42z.js} +2 -2
  44. package/dist/cli/{mcp-qvgka4c8.js → mcp-4q7ntdm7.js} +1 -1
  45. package/dist/cli/{model-preflight-2mvdbj0c.js → model-preflight-ap5k7585.js} +1 -1
  46. package/dist/cli/{pending-delegations-1xvmbw29.js → pending-delegations-52t70c1w.js} +2 -2
  47. package/dist/cli/{pr-subscriptions-13xqrhwx.js → pr-subscriptions-915nbgys.js} +1 -1
  48. package/dist/cli/{pr-workflow-gate-6qzpckxa.js → pr-workflow-gate-zbaqx5gr.js} +20 -20
  49. package/dist/cli/{scan-cursor-q5nycpzb.js → scan-cursor-922rhxag.js} +2 -2
  50. package/dist/cli/{schema-a8gskpey.js → schema-8r56yn5m.js} +2 -2
  51. package/dist/cli/{scope-persistence-q0n6y3n7.js → scope-persistence-xsxj83mx.js} +6 -6
  52. package/dist/cli/{server-wmbahe8h.js → server-vmdq6des.js} +20 -20
  53. package/dist/cli/{skill-generator-z76whwng.js → skill-generator-q9kmx4yk.js} +8 -8
  54. package/dist/cli/{snapshot-coordination-init-k2fgw463.js → snapshot-coordination-init-0qmg827p.js} +20 -20
  55. package/dist/cli/{worktree-collision-ownership-deyrgr70.js → worktree-collision-ownership-yvth2mxb.js} +2 -2
  56. package/dist/cli/{worktree-isolation-9rjxaxp6.js → worktree-isolation-sqzqrnd6.js} +20 -20
  57. package/dist/index.js +3 -3
  58. 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.172.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; 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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.172.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, 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"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; 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_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -7353,11 +7353,11 @@ MICRO WORKED EXAMPLE:
7353
7353
  ${CANDIDATE_HEADERS.micro_lane}
7354
7354
  [CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
7355
7355
  Zero findings: ${CLEAN_TEMPLATES.micro_lane}
7356
- ${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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),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"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt."),pr_review_contract_retry:exports_external.boolean().optional().describe("PR_REVIEW base-only contract retry marker. Use only for one admitted retry of exactly one dimension whose previous terminal record was a contract failure; it is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt and does not consume staged retry budget.")}),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 _internals249={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep5};class PrReviewStructuredPromptUnsupportedError extends Error{constructor(message="structured PR-review prompt transport is unsupported"){super(message);this.name="PrReviewStructuredPromptUnsupportedError"}}function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;return{enabled:configured.enabled,canary_probe_ms:policy?.canaryProbeMs??configured.canary_probe_ms,status_probe_timeout_ms:policy?.statusProbeTimeoutMs??configured.status_probe_timeout_ms,correlated_failure_threshold:policy?.correlatedFailureThreshold??configured.correlated_failure_threshold,max_retry_attempts_after_initial:policy?.maxRetryAttemptsAfterInitial??configured.max_retry_attempts_after_initial,circuit_open_duration_ms:policy?.circuitOpenDurationMs??configured.circuit_open_duration_ms}}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=_internals249.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);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=_internals249.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=_internals249.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId,duplicateRead=findByBatchIdDetailed(directory,batchId);if(duplicateRead.status==="uncertain")return asyncFailureResult({failure_class:"invalid_args",message:`batch uniqueness unverifiable: delegation store unreadable after ${duplicateRead.attempts} attempts (${duplicateRead.reason})`,errors:[`batch_id uniqueness could not be verified: ${batchId}; retry once the delegation store is readable`]});if(duplicateRead.value.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,prReviewWorkflowInstanceId,prReviewWorkflowRevision,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((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(parsed.data.pr_review_contract_retry&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_contract_retry is valid only when mode is exactly "swarm-pr-review:base".'});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=_internals249.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals249.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest5)=>digest5?{ok:!0,digest:digest5}:{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 _internals249.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 using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: 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 formatExplorerLanes=(input)=>applyExplorerFormatSuffix(input,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode}),contractPromptLanes=(input)=>applyPrWorkflowPromptContract(input,{mode:parsed.data.mode,batchId:parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro"?batchId:void 0,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(parsed.data.pr_review_wave_stage==="fanout"||parsed.data.mode==="swarm-pr-review:base"&&parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??0)>1)){let formatted=formatExplorerLanes(lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});let contracted=contractPromptLanes(formatted.lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=contracted.lanes}else{let contracted=contractPromptLanes(lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=formatExplorerLanes(contracted.lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});lanes=formatted.lanes}if(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"){let configuredResilience=_internals249.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),contractRetry=parsed.data.pr_review_contract_retry===!0,waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(contractRetry&&(waveStage!==void 0||waveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&!contractRetry&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){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); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}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; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires 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`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(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),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}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:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"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=_internals249.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,prReviewWorkflowInstanceId,prReviewWorkflowRevision}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&(parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_contract_retry===!0))try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId,parsed.data.pr_review_contract_retry===!0)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected2.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected2.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 timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals249.now()+timeoutMs,hostTimeouts=new Set,collectionResourceFailures=new Map,receiptAppendFailureLogs=new Set,settleFailureLogs=new Map,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,initialRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(initialRead.status==="uncertain")return collectFailureResult({failure_class:"store_unreadable",batch_id:parsed.data.batch_id,message:`Delegation store unreadable after ${initialRead.attempts} attempts; batch ${parsed.data.batch_id} is UNKNOWN, not absent (${initialRead.reason})`});let records=initialRead.value;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}`});await recoverTerminalLaneReceipts(directory,records);let revisionSnapshots=new Map,session=_internals249.getSessionOps();if(!session||typeof session.messages!=="function"){let reviewReceiptFallbacks2=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result2=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks2}),observed=reducePrReviewEvent({sessionID:context.sessionID??"",revision:0},{type:"collection_observed",diagnostic:"host_unavailable",pendingLaneIds:records.filter((record3)=>!isTerminalDelegationStatus2(record3.status)).map((record3)=>record3.laneId??record3.correlationId)}),diagnosticCode=observed.status==="applied"?observed.effects.find((effect)=>effect.kind==="emit_diagnostic")?.code??"collection_host_unavailable":"collection_host_unavailable";return result2.failure_class="no_client",result2.message="OpenCode session messages client is not available; lane state is reported as stored and no lane was cancelled or terminalized. Poll again once the host client is available, cancel explicitly, or rely on the presumed-stale backstop.",result2.errors=[`OpenCode session messages client is not available (${diagnosticCode})`],await attachPendingLaneLiveness(result2,directory,records,deadline),result2}let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts);let pollRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(pollRead.status==="uncertain"){if(addLaneDiagnostic(collectionResourceFailures,`batch:${parsed.data.batch_id}`,`collect re-read uncertain: delegation store unreadable after ${pollRead.attempts} attempts (${pollRead.reason}); settlement UNKNOWN, continuing to poll`),parsed.data.wait!==!0){keepPolling=!1;continue}}else if(records=pollRead.value,allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals249.now()>=deadline){keepPolling=!1;continue}await _internals249.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals249.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(await attachPendingLaneLiveness(result,directory,records,deadline),hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.";let diagnostics=assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures);if(diagnostics.length>0)result.errors=diagnostics;return result}async function attachPendingLaneLiveness(result,directory,records,deadline){if(result.pending<=0)return;let pendingLiveness=await collectPrWorkflowPendingLaneLiveness(directory,records,{probeBudgetMs:Math.max(0,deadline-_internals249.now())});if(pendingLiveness.length>0)result.pending_liveness=pendingLiveness}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:key2}=current;if((key2==="isRetryable"||key2==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key2===void 0||CREATE_FAILURE_STATUS_KEYS.has(key2)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key2!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key2))continue;if(key2!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key2)&&/^\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:key2})}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,legacyTranscriptCompatibility=args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"?prReviewLegacyTranscriptCompatibilityEnabled(_internals249.loadPluginConfig(args2.directory).pr_review_legacy_transcript_compatibility):void 0,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:args2.prReviewWorkflowInstanceId?encodePrReviewWorkflowBinding(args2.prReviewWorkflowInstanceId):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,prReviewLegacyTranscriptCompatibility:legacyTranscriptCompatibility,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},...args2.prReviewWorkflowRevision!==void 0?{workflowGeneration:args2.prReviewWorkflowRevision}:{},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 emitDelegationBegin(pendingOutcome.record),scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs,mode:args2.mode,structuredAdapter:args2.context.prReviewStructuredPromptAdapter}),{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,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],laneLabel=record3.laneId??record3.correlationId,remainingLaneCount=activeRecords.length-index,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,typeof session.status==="function",needsRevisionDigest);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,laneBudgets.laneBudgetMs)}catch{if(hostTimeouts.size>timeoutCount)continue}}await settleDelegationTerminal(directory,record3,{status:"cancelled",result:{error:"lane cancelled via collect_lane_results cancel_pending",chars:0,truncated:!1,digest:digestText2("")}},{},_internals249.now());continue}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")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 "${laneLabel}"`,hostTimeouts,laneBudgets.messagesBudgetMs)}catch(error93){let messageTimeoutPrefix=`session.messages for lane "${laneLabel}" exceeded the remaining collect_lane_results budget`;if(![...hostTimeouts].some((entry)=>entry.startsWith(messageTimeoutPrefix)))addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages transport error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);continue}if(!messages.data){if(messages.error)addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages returned an error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(messages.error)}`);continue}clearLaneDiagnostics(collectionResourceFailures,laneLabel);let transcript=extractAssistantTranscript(messages.data),relyingOnCompletedAtOnly=readiness!=="idle"&&Number.isFinite(transcript.completedAt),hostSaysRetryable=transcript.terminalError?.kind!=="aborted"&&transcript.terminalError?.hostRetryable===!0;if(transcript.terminalError&&!transcript.text&&!transcript.windowTruncated&&(Number.isFinite(transcript.completedAt)||readiness==="idle")&&!(relyingOnCompletedAtOnly&&hostSaysRetryable)){let settledStatus=transcript.terminalError.kind==="aborted"?"cancelled":"error",reason=laneTerminalErrorReason(transcript.terminalError),settled=await settleDelegationTerminal(directory,record3,{status:settledStatus,result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),terminalErrorClass:terminalErrorClassFromLaneTerminalError(transcript.terminalError)}},{},_internals249.now());if(settled.kind==="claimed")clearLaneDiagnostics(settleFailureLogs,laneLabel),cleanupAsyncLaunchSession(session,record3.subagentSessionId);else if(isBenignSettleOutcome(settled.kind))clearLaneDiagnostics(settleFailureLogs,laneLabel);else if(settled.kind==="uncertain")addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle deferred for lane "${laneLabel}"; delegation store unreadable (${settled.reason??"unclassified"}); lane left open for retry`);else addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle write did not land for lane "${laneLabel}"; lane left open`);continue}if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}))}await Promise.all(pendingSettlements)}function revisionSnapshotKey(directory,prHeadSha){return`${canonicalRootKeyFresh(directory)}\x00${prHeadSha??""}`}var MAX_DIAGNOSTICS_PER_LANE=3,MAX_HOST_TIMEOUT_DIAGNOSTICS=MAX_LANES*4,MAX_LANE_DIAGNOSTICS_PER_CHANNEL=MAX_LANES*MAX_DIAGNOSTICS_PER_LANE;function assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures){return[...flattenLaneDiagnostics(settleFailureLogs),...flattenLaneDiagnostics(collectionResourceFailures),...[...hostTimeouts].slice(0,MAX_HOST_TIMEOUT_DIAGNOSTICS)]}function addLaneDiagnostic(diagnostics,laneLabel,message){let entries2=diagnostics.get(laneLabel);if(entries2===void 0)entries2=new Set,diagnostics.set(laneLabel,entries2);if(entries2.has(message))return;if(entries2.size>=MAX_DIAGNOSTICS_PER_LANE)return;entries2.add(message)}function clearLaneDiagnostics(diagnostics,laneLabel){diagnostics.delete(laneLabel)}function flattenLaneDiagnostics(diagnostics){let flat=[];for(let entries2 of diagnostics.values())for(let entry of entries2){if(flat.length>=MAX_LANE_DIAGNOSTICS_PER_CHANNEL)return flat;flat.push(entry)}return flat}var MAX_DIAGNOSTIC_CAUSE_CHARS=160;function safeDiagnosticCause(error93){let redacted=sanitizeFailureEvidenceDisplay(formatError3(error93));if(redacted.length===0)return"(no detail)";return redacted.length>MAX_DIAGNOSTIC_CAUSE_CHARS?`${redacted.slice(0,MAX_DIAGNOSTIC_CAUSE_CHARS)}…`:redacted}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}=args2,laneLabel=record3.laneId??record3.correlationId,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{let key2=revisionSnapshotKey(directory,prHeadSha),snapshot2=revisionSnapshots.get(key2);if(snapshot2===void 0){snapshot2=_internals249.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha);let pending=snapshot2;pending.catch(()=>{if(revisionSnapshots.get(key2)===pending)revisionSnapshots.delete(key2)}),revisionSnapshots.set(key2,pending)}let shared=snapshot2;collectedRevisionDigest=await withCollectionDeadline(()=>shared,deadline,`revision digest for lane "${laneLabel}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch(error93){addLaneDiagnostic(settleFailureLogs,laneLabel,`revision snapshot unavailable for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);return}clearLaneDiagnostics(settleFailureLogs,laneLabel);let 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,...record3.result?.prReviewResultReceipt?{prReviewResultReceipt:record3.result.prReviewResultReceipt}:{}},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion2({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){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error",prospectiveResult.workflowLaneFailureClass="contract";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)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals249.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{},_internals249.now());return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode2=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode2}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{transcript:transcript.text,startedAt:record3.createdAt,model:laneConfiguredModel(record3)},_internals249.now())}function laneConfiguredModel(record3){let prefixed=record3.swarmPrefixedAgent,baseRole=stripKnownSwarmPrefix(prefixed),swarmID=baseRole!==prefixed?prefixed.slice(0,prefixed.length-baseRole.length-1):void 0;return getSwarmAgents(swarmID)?.[baseRole]?.model}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key2=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key2))return!1;return loggedFailures.add(key2),!0}class LanePromptLaunchRejectionError extends Error{constructor(message){super(message);this.name="LanePromptLaunchRejectionError"}}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){if(args2.structuredAdapter&&(args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"))try{await withTimeout2(args2.structuredAdapter.promptJsonSchema({sessionId:args2.sessionId,agent:args2.lane.agent,schema:exports_external.toJSONSchema(PrReviewLaneResultEnvelopeSchema),parts:[{type:"text",text:args2.lane.prompt}]}),args2.timeoutMs,`Lane "${args2.lane.id}" structured PR-review launch timed out after ${args2.timeoutMs}ms`);return}catch(error93){if(!(error93 instanceof PrReviewStructuredPromptUnsupportedError)){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}}let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(args2.mode),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw new LanePromptLaunchRejectionError(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals249.now()+args2.timeoutMs,now:_internals249.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}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){let recordRead=findByCorrelationIdDetailed(directory,sessionId);if(recordRead.status==="uncertain"){warnDelegationReadUncertainOnce2(`launch-error settle skipped for lane session ${sessionId}`,recordRead),cleanupAsyncLaunchSession(session,sessionId);return}let record3=recordRead.value,isPrReviewLane=record3?.mode?.startsWith("swarm-pr-review:")===!0,launchErrorResult={error:message,chars:message.length,truncated:!1,digest:digestText2(message),...isPrReviewLane?{workflowLaneFailureClass:"resource"}:{}};if(record3)await settleDelegationTerminal(directory,record3,{status:"error",result:launchErrorResult},{},_internals249.now());else await appendDelegationTransition(directory,sessionId,{status:"error",result:launchErrorResult});cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";if(statusBudgetMs<=0)return"unknown";try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status.error||!status.data)return"unknown";let current=status.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}var DELEGATION_READ_UNCERTAIN_LOG_LIMIT2=64,delegationReadUncertainLogged2=new Set;function warnDelegationReadUncertainOnce2(label,uncertain){let key2=`${label}\x00${uncertain.reason}`;if(delegationReadUncertainLogged2.has(key2))return;if(delegationReadUncertainLogged2.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT2){let oldest=delegationReadUncertainLogged2.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged2.delete(oldest)}delegationReadUncertainLogged2.add(key2),warn(`${label}: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); skipping this pass`)}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals249.now();for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;if(await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs)!=="idle")continue;let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&&current.status!=="running"&&current.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),status=error93.statusCode===void 0?"":` status=${error93.statusCode}`,retryable=error93.hostRetryable===void 0?"":` host_retryable=${error93.hostRetryable}`;return`${error93.category}: ${message} [kind=${error93.kind} name=${error93.name}${status}${retryable}]`}function terminalErrorClassFromLaneTerminalError(error93){let category=error93.category.trim().length>0?error93.category.trim().slice(0,128):"unknown";return{kind:error93.kind,category,...error93.statusCode===void 0?{}:{statusCode:error93.statusCode},...error93.hostRetryable===void 0?{}:{hostRetryable:error93.hostRetryable}}}function readErrorDataRecord(error93){if(typeof error93!=="object"||error93===null)return{};let data=error93.data;return typeof data==="object"&&data!==null?data:{}}function classifyLaneTerminalError(error93){let name=typeof error93?.name==="string"?error93.name.slice(0,64):"UnknownError",data=readErrorDataRecord(error93),topLevelMessage=error93?.message,rawMessage=typeof data.message==="string"&&data.message.trim().length>0?data.message:typeof topLevelMessage==="string"&&topLevelMessage.trim().length>0?topLevelMessage:typeof error93==="string"&&error93.trim().length>0?error93:name,statusCode=typeof data.statusCode==="number"&&Number.isFinite(data.statusCode)?data.statusCode:void 0,hostRetryable=typeof data.isRetryable==="boolean"?data.isRetryable:void 0,kind=name==="MessageAbortedError"?"aborted":name==="MessageOutputLengthError"?"output_length":name==="APIError"||name==="ProviderAuthError"?"provider":"unknown",classified=classifyProviderFailure(statusCode===void 0?rawMessage:{message:rawMessage,status:statusCode}),category=kind==="aborted"?"provider.cancelled":classified.category;return{kind,name,message:classified.evidence.display,statusCode:statusCode??classified.evidence.statusCode,hostRetryable,category}}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
7356
+ ${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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),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"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt."),pr_review_contract_retry:exports_external.boolean().optional().describe("PR_REVIEW base-only contract retry marker. Use only for one admitted retry of exactly one dimension whose previous terminal record was a contract failure; it is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt and does not consume staged retry budget.")}),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 _internals249={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep5};class PrReviewStructuredPromptUnsupportedError extends Error{constructor(message="structured PR-review prompt transport is unsupported"){super(message);this.name="PrReviewStructuredPromptUnsupportedError"}}function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;return{enabled:configured.enabled,canary_probe_ms:policy?.canaryProbeMs??configured.canary_probe_ms,status_probe_timeout_ms:policy?.statusProbeTimeoutMs??configured.status_probe_timeout_ms,correlated_failure_threshold:policy?.correlatedFailureThreshold??configured.correlated_failure_threshold,max_retry_attempts_after_initial:policy?.maxRetryAttemptsAfterInitial??configured.max_retry_attempts_after_initial,circuit_open_duration_ms:policy?.circuitOpenDurationMs??configured.circuit_open_duration_ms}}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=_internals249.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);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=_internals249.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=_internals249.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId,duplicateRead=findByBatchIdDetailed(directory,batchId);if(duplicateRead.status==="uncertain")return asyncFailureResult({failure_class:"invalid_args",message:`batch uniqueness unverifiable: delegation store unreadable after ${duplicateRead.attempts} attempts (${duplicateRead.reason})`,errors:[`batch_id uniqueness could not be verified: ${batchId}; retry once the delegation store is readable`]});if(duplicateRead.value.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,prReviewWorkflowInstanceId,prReviewWorkflowRevision,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((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(parsed.data.pr_review_contract_retry&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_contract_retry is valid only when mode is exactly "swarm-pr-review:base".'});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=_internals249.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals249.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest5)=>digest5?{ok:!0,digest:digest5}:{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 _internals249.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 using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: 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 formatExplorerLanes=(input)=>applyExplorerFormatSuffix(input,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode}),contractPromptLanes=(input)=>applyPrWorkflowPromptContract(input,{mode:parsed.data.mode,batchId:parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro"?batchId:void 0,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(parsed.data.pr_review_wave_stage==="fanout"||parsed.data.mode==="swarm-pr-review:base"&&parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??0)>1)){let formatted=formatExplorerLanes(lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});let contracted=contractPromptLanes(formatted.lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=contracted.lanes}else{let contracted=contractPromptLanes(lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=formatExplorerLanes(contracted.lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});lanes=formatted.lanes}if(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"){let configuredResilience=_internals249.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),contractRetry=parsed.data.pr_review_contract_retry===!0,waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(contractRetry&&(waveStage!==void 0||waveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&!contractRetry&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){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); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}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; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires 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`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(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),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}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:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"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=_internals249.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,prReviewWorkflowInstanceId,prReviewWorkflowRevision}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&(parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_contract_retry===!0))try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId,parsed.data.pr_review_contract_retry===!0)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected2.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected2.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 timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals249.now()+timeoutMs,hostTimeouts=new Set,collectionResourceFailures=new Map,receiptAppendFailureLogs=new Set,settleFailureLogs=new Map,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,initialRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(initialRead.status==="uncertain")return collectFailureResult({failure_class:"store_unreadable",batch_id:parsed.data.batch_id,message:`Delegation store unreadable after ${initialRead.attempts} attempts; batch ${parsed.data.batch_id} is UNKNOWN, not absent (${initialRead.reason})`});let records=initialRead.value;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}`});await recoverTerminalLaneReceipts(directory,records);let revisionSnapshots=new Map,session=_internals249.getSessionOps();if(!session||typeof session.messages!=="function"){let reviewReceiptFallbacks2=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result2=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks2}),observed=reducePrReviewEvent({sessionID:context.sessionID??"",revision:0},{type:"collection_observed",diagnostic:"host_unavailable",pendingLaneIds:records.filter((record3)=>!isTerminalDelegationStatus2(record3.status)).map((record3)=>record3.laneId??record3.correlationId)}),diagnosticCode=observed.status==="applied"?observed.effects.find((effect)=>effect.kind==="emit_diagnostic")?.code??"collection_host_unavailable":"collection_host_unavailable";return result2.failure_class="no_client",result2.message="OpenCode session messages client is not available; lane state is reported as stored and no lane was cancelled or terminalized. Poll again once the host client is available, cancel explicitly, or rely on the presumed-stale backstop.",result2.errors=[`OpenCode session messages client is not available (${diagnosticCode})`],await attachPendingLaneLiveness(result2,directory,records,deadline),result2}let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts);let pollRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(pollRead.status==="uncertain"){if(addLaneDiagnostic(collectionResourceFailures,`batch:${parsed.data.batch_id}`,`collect re-read uncertain: delegation store unreadable after ${pollRead.attempts} attempts (${pollRead.reason}); settlement UNKNOWN, continuing to poll`),parsed.data.wait!==!0){keepPolling=!1;continue}}else if(records=pollRead.value,allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals249.now()>=deadline){keepPolling=!1;continue}await _internals249.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals249.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(await attachPendingLaneLiveness(result,directory,records,deadline),hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.";let diagnostics=assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures);if(diagnostics.length>0)result.errors=diagnostics;return result}async function attachPendingLaneLiveness(result,directory,records,deadline){if(result.pending<=0)return;let pendingLiveness=await collectPrWorkflowPendingLaneLiveness(directory,records,{probeBudgetMs:Math.max(0,deadline-_internals249.now())});if(pendingLiveness.length>0)result.pending_liveness=pendingLiveness}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:key2}=current;if((key2==="isRetryable"||key2==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key2===void 0||CREATE_FAILURE_STATUS_KEYS.has(key2)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key2!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key2))continue;if(key2!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key2)&&/^\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:key2})}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,legacyTranscriptCompatibility=args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"?prReviewLegacyTranscriptCompatibilityEnabled(_internals249.loadPluginConfig(args2.directory).pr_review_legacy_transcript_compatibility):void 0,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:args2.prReviewWorkflowInstanceId?encodePrReviewWorkflowBinding(args2.prReviewWorkflowInstanceId):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,prReviewLegacyTranscriptCompatibility:legacyTranscriptCompatibility,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},...args2.prReviewWorkflowRevision!==void 0?{workflowGeneration:args2.prReviewWorkflowRevision}:{},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 emitDelegationBegin(pendingOutcome.record),scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs,mode:args2.mode,structuredAdapter:args2.context.prReviewStructuredPromptAdapter}),{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,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],laneLabel=record3.laneId??record3.correlationId,remainingLaneCount=activeRecords.length-index,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,typeof session.status==="function",needsRevisionDigest);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,laneBudgets.laneBudgetMs)}catch{if(hostTimeouts.size>timeoutCount)continue}}await settleDelegationTerminal(directory,record3,{status:"cancelled",result:{error:"lane cancelled via collect_lane_results cancel_pending",chars:0,truncated:!1,digest:digestText2("")}},{},_internals249.now());continue}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")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 "${laneLabel}"`,hostTimeouts,laneBudgets.messagesBudgetMs)}catch(error93){let messageTimeoutPrefix=`session.messages for lane "${laneLabel}" exceeded the remaining collect_lane_results budget`;if(![...hostTimeouts].some((entry)=>entry.startsWith(messageTimeoutPrefix)))addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages transport error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);continue}if(!messages.data){if(messages.error)addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages returned an error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(messages.error)}`);continue}clearLaneDiagnostics(collectionResourceFailures,laneLabel);let transcript=extractAssistantTranscript(messages.data),relyingOnCompletedAtOnly=readiness!=="idle"&&Number.isFinite(transcript.completedAt),hostSaysRetryable=transcript.terminalError?.kind!=="aborted"&&transcript.terminalError?.hostRetryable===!0;if(transcript.terminalError&&!transcript.text&&!transcript.windowTruncated&&(Number.isFinite(transcript.completedAt)||readiness==="idle")&&!(relyingOnCompletedAtOnly&&hostSaysRetryable)){let settledStatus=transcript.terminalError.kind==="aborted"?"cancelled":"error",reason=laneTerminalErrorReason(transcript.terminalError),settled=await settleDelegationTerminal(directory,record3,{status:settledStatus,result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),terminalErrorClass:terminalErrorClassFromLaneTerminalError(transcript.terminalError)}},{},_internals249.now());if(settled.kind==="claimed")clearLaneDiagnostics(settleFailureLogs,laneLabel),cleanupAsyncLaunchSession(session,record3.subagentSessionId);else if(isBenignSettleOutcome(settled.kind))clearLaneDiagnostics(settleFailureLogs,laneLabel);else if(settled.kind==="uncertain")addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle deferred for lane "${laneLabel}"; delegation store unreadable (${settled.reason??"unclassified"}); lane left open for retry`);else addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle write did not land for lane "${laneLabel}"; lane left open`);continue}if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}))}await Promise.all(pendingSettlements)}function revisionSnapshotKey(directory,prHeadSha){return`${canonicalRootKeyFresh(directory)}\x00${prHeadSha??""}`}var MAX_DIAGNOSTICS_PER_LANE=3,MAX_HOST_TIMEOUT_DIAGNOSTICS=MAX_LANES*4,MAX_LANE_DIAGNOSTICS_PER_CHANNEL=MAX_LANES*MAX_DIAGNOSTICS_PER_LANE;function assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures){return[...flattenLaneDiagnostics(settleFailureLogs),...flattenLaneDiagnostics(collectionResourceFailures),...[...hostTimeouts].slice(0,MAX_HOST_TIMEOUT_DIAGNOSTICS)]}function addLaneDiagnostic(diagnostics,laneLabel,message){let entries2=diagnostics.get(laneLabel);if(entries2===void 0)entries2=new Set,diagnostics.set(laneLabel,entries2);if(entries2.has(message))return;if(entries2.size>=MAX_DIAGNOSTICS_PER_LANE)return;entries2.add(message)}function clearLaneDiagnostics(diagnostics,laneLabel){diagnostics.delete(laneLabel)}function flattenLaneDiagnostics(diagnostics){let flat=[];for(let entries2 of diagnostics.values())for(let entry of entries2){if(flat.length>=MAX_LANE_DIAGNOSTICS_PER_CHANNEL)return flat;flat.push(entry)}return flat}var MAX_DIAGNOSTIC_CAUSE_CHARS=160;function safeDiagnosticCause(error93){let redacted=sanitizeFailureEvidenceDisplay(formatError3(error93));if(redacted.length===0)return"(no detail)";return redacted.length>MAX_DIAGNOSTIC_CAUSE_CHARS?`${redacted.slice(0,MAX_DIAGNOSTIC_CAUSE_CHARS)}…`:redacted}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}=args2,laneLabel=record3.laneId??record3.correlationId,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{let key2=revisionSnapshotKey(directory,prHeadSha),snapshot2=revisionSnapshots.get(key2);if(snapshot2===void 0){snapshot2=_internals249.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha);let pending=snapshot2;pending.catch(()=>{if(revisionSnapshots.get(key2)===pending)revisionSnapshots.delete(key2)}),revisionSnapshots.set(key2,pending)}let shared=snapshot2;collectedRevisionDigest=await withCollectionDeadline(()=>shared,deadline,`revision digest for lane "${laneLabel}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch(error93){addLaneDiagnostic(settleFailureLogs,laneLabel,`revision snapshot unavailable for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);return}clearLaneDiagnostics(settleFailureLogs,laneLabel);let 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,...record3.result?.prReviewResultReceipt?{prReviewResultReceipt:record3.result.prReviewResultReceipt}:{}},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion2({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){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error",prospectiveResult.workflowLaneFailureClass="contract";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)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals249.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{},_internals249.now());return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode2=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode2}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{transcript:transcript.text,startedAt:record3.createdAt,model:laneConfiguredModel(record3)},_internals249.now())}function laneConfiguredModel(record3){let prefixed=record3.swarmPrefixedAgent,baseRole=stripKnownSwarmPrefix(prefixed),swarmID=baseRole!==prefixed?prefixed.slice(0,prefixed.length-baseRole.length-1):void 0;return getSwarmAgents(swarmID)?.[baseRole]?.model}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key2=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key2))return!1;return loggedFailures.add(key2),!0}class LanePromptLaunchRejectionError extends Error{constructor(message){super(message);this.name="LanePromptLaunchRejectionError"}}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){if(args2.structuredAdapter&&(args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"))try{await withTimeout2(args2.structuredAdapter.promptJsonSchema({sessionId:args2.sessionId,agent:args2.lane.agent,schema:exports_external.toJSONSchema(PrReviewLaneResultEnvelopeSchema),parts:[{type:"text",text:args2.lane.prompt}]}),args2.timeoutMs,`Lane "${args2.lane.id}" structured PR-review launch timed out after ${args2.timeoutMs}ms`);return}catch(error93){if(!(error93 instanceof PrReviewStructuredPromptUnsupportedError)){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}}let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),lanePrimaryModel=swarmAgents?.[baseRole]?.model,laneFallbackModels=swarmAgents?.[baseRole]?.fallback_models??[],registry3=_internals249.getGeneratedAgentNames();if(registry3.length>0&&!registry3.some((name)=>name.toLowerCase()===args2.lane.agent.toLowerCase())&&!swarmAgents?.[baseRole]&&!lanePrimaryModel&&laneFallbackModels.length===0){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`Lane "${args2.lane.id}" agent "${args2.lane.agent}" resolves no registered swarm agent and no model; refusing to launch a lane the host cannot run`);return}let promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(args2.mode),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw new LanePromptLaunchRejectionError(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals249.now()+args2.timeoutMs,now:_internals249.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}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){let recordRead=findByCorrelationIdDetailed(directory,sessionId);if(recordRead.status==="uncertain"){warnDelegationReadUncertainOnce2(`launch-error settle skipped for lane session ${sessionId}`,recordRead),cleanupAsyncLaunchSession(session,sessionId);return}let record3=recordRead.value,isPrReviewLane=record3?.mode?.startsWith("swarm-pr-review:")===!0,launchErrorResult={error:message,chars:message.length,truncated:!1,digest:digestText2(message),...isPrReviewLane?{workflowLaneFailureClass:"resource"}:{}};if(record3)await settleDelegationTerminal(directory,record3,{status:"error",result:launchErrorResult},{},_internals249.now());else await appendDelegationTransition(directory,sessionId,{status:"error",result:launchErrorResult});cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";if(statusBudgetMs<=0)return"unknown";try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status.error||!status.data)return"unknown";let current=status.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}var DELEGATION_READ_UNCERTAIN_LOG_LIMIT2=64,delegationReadUncertainLogged2=new Set;function warnDelegationReadUncertainOnce2(label,uncertain){let key2=`${label}\x00${uncertain.reason}`;if(delegationReadUncertainLogged2.has(key2))return;if(delegationReadUncertainLogged2.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT2){let oldest=delegationReadUncertainLogged2.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged2.delete(oldest)}delegationReadUncertainLogged2.add(key2),warn(`${label}: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); skipping this pass`)}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals249.now();for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;if(await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs)!=="idle")continue;let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&&current.status!=="running"&&current.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),status=error93.statusCode===void 0?"":` status=${error93.statusCode}`,retryable=error93.hostRetryable===void 0?"":` host_retryable=${error93.hostRetryable}`;return`${error93.category}: ${message} [kind=${error93.kind} name=${error93.name}${status}${retryable}]`}function terminalErrorClassFromLaneTerminalError(error93){let category=error93.category.trim().length>0?error93.category.trim().slice(0,128):"unknown";return{kind:error93.kind,category,...error93.statusCode===void 0?{}:{statusCode:error93.statusCode},...error93.hostRetryable===void 0?{}:{hostRetryable:error93.hostRetryable}}}function readErrorDataRecord(error93){if(typeof error93!=="object"||error93===null)return{};let data=error93.data;return typeof data==="object"&&data!==null?data:{}}function classifyLaneTerminalError(error93){let name=typeof error93?.name==="string"?error93.name.slice(0,64):"UnknownError",data=readErrorDataRecord(error93),topLevelMessage=error93?.message,rawMessage=typeof data.message==="string"&&data.message.trim().length>0?data.message:typeof topLevelMessage==="string"&&topLevelMessage.trim().length>0?topLevelMessage:typeof error93==="string"&&error93.trim().length>0?error93:name,statusCode=typeof data.statusCode==="number"&&Number.isFinite(data.statusCode)?data.statusCode:void 0,hostRetryable=typeof data.isRetryable==="boolean"?data.isRetryable:void 0,kind=name==="MessageAbortedError"?"aborted":name==="MessageOutputLengthError"?"output_length":name==="APIError"||name==="ProviderAuthError"?"provider":"unknown",classified=classifyProviderFailure(statusCode===void 0?rawMessage:{message:rawMessage,status:statusCode}),category=kind==="aborted"?"provider.cancelled":classified.category;return{kind,name,message:classified.evidence.display,statusCode:statusCode??classified.evidence.statusCode,hostRetryable,category}}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
7357
7357
 
7358
7358
  `),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT||finish==="length"||finish==="content-filter",terminalAssistantProof:typeof completedAt==="number"&&Number.isFinite(completedAt)&&terminalAssistantFinish&&lastAssistantInfo?.error===void 0,completedAt:typeof completedAt==="number"?completedAt:void 0,windowTruncated:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT,terminalError:lastAssistantInfo?.error===void 0?void 0:classifyLaneTerminalError(lastAssistantInfo.error)}}function reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,hasStatusCall,hasRevisionDigestCall=!1){let remainingMs2=Math.max(0,deadline-_internals249.now());if(remainingMs2===0)return{laneBudgetMs:0,statusBudgetMs:0,messagesBudgetMs:0,revisionDigestBudgetMs:0};let laneBudgetMs=Math.min(remainingMs2,Math.max(1,Math.floor(remainingMs2/Math.max(1,remainingLaneCount)))),callCount=1+Number(hasStatusCall)+Number(hasRevisionDigestCall),statusBudgetMs=hasStatusCall?Math.min(MAX_STATUS_CALL_BUDGET_MS,Math.floor(laneBudgetMs/callCount)):0,afterStatusMs=laneBudgetMs-statusBudgetMs,revisionDigestBudgetMs=hasRevisionDigestCall?Math.floor(afterStatusMs/2):0;return{laneBudgetMs,statusBudgetMs,messagesBudgetMs:afterStatusMs-revisionDigestBudgetMs,revisionDigestBudgetMs}}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(),syncClassifiedReason;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,lifecycleRecordPromise=Promise.resolve(null);try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let createdSessionId=sessionId;lifecycleRecordPromise=recordPendingDelegationDetailed(directory,{correlationId:createdSessionId,jobId:null,subagentSessionId:createdSessionId,parentSessionId:context.sessionID?.trim()||`dispatch_lanes:${createdSessionId}`,callID:`blocking:${createdSessionId}`,normalizedAgent:role,swarmPrefixedAgent:lane.agent,planTaskId:null,evidenceTaskId:null,laneId:lane.id,mode:"blocking",promptHash:promptHash(lane,directory,`blocking:${createdSessionId}`),workspace:{directory,gitHead:null,dirtyHash:null,prHeadSha:null,scope:null},generation:create.generation}).then((pendingOutcome)=>{if(pendingOutcome.status==="recorded")return emitDelegationBegin(pendingOutcome.record),pendingOutcome.record;return log(`[dispatch-lanes] blocking lane start record did not land (status ${pendingOutcome.status}); lane ${lane.id} proceeds without durable lifecycle`),null});let baseRole=stripKnownSwarmPrefix(lane.agent),swarmID=baseRole!==lane.agent?lane.agent.slice(0,lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult=(await dispatchWithModelFallback({dispatch:async(model,context2)=>{syncClassifiedReason=void 0;let result=await withTimeout2(session.prompt({path:{id:createdSessionId},body:{agent:lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),context2.remainingMs??timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${context2.remainingMs??timeoutMs}ms`,promptController);if(!result.data)throw syncClassifiedReason=`session.prompt failed: ${laneTerminalErrorReason(classifyLaneTerminalError(result.error))}`,new LanePromptLaunchRejectionError(`session.prompt failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals249.now()+timeoutMs,now:_internals249.now,scope:{sessionID:sessionId,invocationID:`dispatch-lanes-sync:${lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result;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)}),lifecycleRecord=await lifecycleRecordPromise;if(lifecycleRecord)await settleDelegationTerminal(directory,lifecycleRecord,{status:"completed",result:{text:laneOutput.output,chars:laneOutput.output_chars,truncated:laneOutput.output_truncated,digest:laneOutput.output_digest,...laneOutput.output_ref?{outputRef:laneOutput.output_ref}:{}}},{transcript:laneOutput.output,startedAt:Date.parse(startedAt)||void 0,model:swarmAgents?.[baseRole]?.model},_internals249.now());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){let lifecycleRecord=await lifecycleRecordPromise.catch(()=>null);if(lifecycleRecord){let failureReason=syncClassifiedReason??formatError3(error93);await settleDelegationTerminal(directory,lifecycleRecord,{status:"error",result:{error:failureReason.slice(0,MAX_ERROR_CHARS),chars:failureReason.length,truncated:failureReason.length>MAX_ERROR_CHARS,digest:digestText2(failureReason)}},{startedAt:Date.parse(startedAt)||void 0},_internals249.now())}return failedLane(lane,role,startedAt,syncClassifiedReason??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"),rejected2=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected2.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected2.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending,deliveryContext){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId,deliveryContext)),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"),pendingLanes=pending.map((record3)=>({batch_id:batchId,lane_id:record3.laneId??record3.correlationId,status:record3.status,...record3.result?.outputRef?{output_ref:record3.result.outputRef}:{}}));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,...pendingLanes.length>0?{pending_lanes:pendingLanes}:{}}}async function resolvePrReviewReceiptFallbacks(directory,sessionID,records){let receipts=new Map;if(!sessionID)return receipts;let unresolved=records.filter((record3)=>(record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic")&&!parsePrReviewCollectionReceipt(record3)&&record3.result!==void 0&&parsePrReviewCollectionReceiptShedMarker(record3,record3.result)!==null);if(unresolved.length===0)return receipts;let state;try{state=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return log(`[dispatch-lanes] unable to reconstruct compacted PR-review receipts: ${formatError3(error93)}`),receipts}if(!state||state.mode!=="PR_REVIEW")return receipts;return resolvePrReviewReceiptFallbacksFromState(unresolved,state)}function resolvePrReviewReceiptFallbacksFromState(records,state){let receipts=new Map;for(let record3 of records){let phase=record3.mode==="swarm-pr-review:reviewer"?"reviewer":record3.mode==="swarm-pr-review:critic"?"critic":null;if(!phase||!record3.batchId||!record3.laneId)continue;if(record3.status!=="completed"&&record3.status!=="error"&&record3.status!=="ingestion_error"&&record3.status!=="cancelled"&&record3.status!=="stale")continue;let itemIds=(state.prReviewValidationBatches??[]).find((batch)=>batch.batchId===record3.batchId&&batch.phase===phase)?.lanes.find((candidate2)=>candidate2.laneId===record3.laneId&&candidate2.workflowLane===record3.workflowLane)?.reviewItemIds??[];if(itemIds.length===0)continue;let marker=record3.result?parsePrReviewCollectionReceiptShedMarker(record3,record3.result):null,projected=marker?projectPrReviewCollectionReceiptShedMarker(marker,itemIds):null;if(projected)receipts.set(record3.correlationId,projected)}return receipts}function appendPrReviewCollectionReceipt(record3,result,receipt){let sanitizedPreview=(result.text??"").split(/\r?\n/).filter((line)=>!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)&&!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)).join(`
7359
7359
  `),footer=encodePrReviewCollectionReceiptFooter(record3,result,receipt)??encodePrReviewCollectionReceiptShedMarkerFromReceipt(record3,result,receipt);if(!footer)return null;let text=sanitizedPreview?`${sanitizedPreview}
7360
- ${footer}`:footer;return{...result,text,outputPreviewChars:text.length}}function parsePrReviewCollectionReceipt(record3){if(!record3.result)return null;let payload=parsePrReviewCollectionReceiptFooter(record3,record3.result);return payload?projectPrReviewCollectionReceipt(payload):null}function recordToLaneResult(record3,batchId,deliveryContext){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,digest5=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1,reviewReceipt=parsePrReviewCollectionReceipt(record3)??deliveryContext?.reviewReceipts?.get(record3.correlationId);if(record3.result?.text!==void 0&&status!=="pending"&&digest5&&outputRef){let key2=`${batchId}\x00${laneId}\x00${digest5}`;if(alreadyDelivered=hasLaneOutputBeenDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2),!alreadyDelivered)markLaneOutputDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2)}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.workflowLaneFailureClass!==void 0?{workflow_lane_failure_class:record3.result.workflowLaneFailureClass}:{},...record3.result.salvagedWorkflowLanes?.length?{salvaged_workflow_lanes:[...record3.result.salvagedWorkflowLanes]}:{},...record3.result.salvagedWorkflowLaneRecoveries?.length?{salvaged_workflow_lane_recoveries:record3.result.salvagedWorkflowLaneRecoveries.map((recovery)=>({workflow_lane:recovery.workflowLane,kind:recovery.kind,reason:recovery.reason}))}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{},...reviewReceipt?{accepted_review_item_ids:[...reviewReceipt.acceptedReviewItemIds],rejected_review_item_ids:[...reviewReceipt.rejectedReviewItemIds]}:{}}}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=_internals249.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(mode){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;if(tools.write=!1,tools.edit=!1,tools.patch=!1,mode==="swarm-pr-review:base"||mode==="swarm-pr-review:micro")for(let toolName of PR_REVIEW_CHILD_AGENT_TOOL_MAP.explorer??[])tools[toolName]=!0;return 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}}var ORIENTATION_SUFFIX_RESERVE_CHARS=5000;async function augmentCommonPromptWithOrientation(directory,lanes,commonPrompt,orientation,sessionID,deps){if(orientation===!1)return commonPrompt;let buildBlock=deps?.buildBlock??buildLaneOrientationBlock,block=null;try{block=await buildBlock(directory,lanes.map((lane)=>lane.prompt),sessionID?{sessionID}:void 0)}catch(error93){return log("lane orientation block failed open",{error:error93 instanceof Error?error93.message:String(error93)}),commonPrompt}if(!block)return commonPrompt;let combined=commonPrompt?`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${block}`:block;if(lanes.some((lane)=>combined.length+COMMON_PROMPT_SEPARATOR.length+lane.prompt.length+ORIENTATION_SUFFIX_RESERVE_CHARS>MAX_PROMPT_CHARS))return log("lane orientation block dropped: combined common_prompt + orientation + lane prompt + suffix reserve would exceed MAX_PROMPT_CHARS",{maxPromptChars:MAX_PROMPT_CHARS,blockChars:block.length}),commonPrompt;return combined}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=_internals249.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 isPrReviewDiscovery=options.mode==="swarm-pr-review:base"||options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer,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.",exactLaneInput=lane.workflow_lane??lane.id,exactLaneResult=classifyControllerTokenField(exactLaneInput);if(!exactLaneResult.ok){let reason=exactLaneResult.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" workflow_lane ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned,index)=>({index,result:classifyControllerTokenField(owned)})):[{index:0,result:exactLaneResult}],invalidOwnedLane=ownedLaneResults.find(({result})=>!result.ok);if(invalidOwnedLane){let reason=!invalidOwnedLane.result.ok&&invalidOwnedLane.result.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" owned_workflow_lanes[${invalidOwnedLane.index}] ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLanes=ownedLaneResults.map(({result})=>result.ok?result.token:""),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}if(isPrReviewDiscovery){let encouragesVerbatimShellQuoting=/(?:\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b.{0,80}\b(?:faithfully|verbatim|exactly|literally)\b|\b(?:faithfully|verbatim|exactly|literally)\b.{0,80}\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b)/i.test(lane.prompt),forbidden=[lane.prompt.includes(CANDIDATE_HEADERS.base_explorer)?"the canonical base discovery header":null,lane.prompt.includes(CANDIDATE_HEADERS.micro_lane)?"the canonical micro discovery header":null,/\[CANDIDATE\]/.test(lane.prompt)?"[CANDIDATE]":null,/\[CLEAN\]/.test(lane.prompt)?"[CLEAN]":null,encouragesVerbatimShellQuoting?"verbatim shell or pipeline quoting guidance":null].find((value)=>value!==null);if(forbidden)return errors5.push(`Lane "${lane.id}" operator prompt contains ${forbidden}; PR-review discovery prompts carry content only and the controller injects the authoritative output contract`),lane}let prompt=`${lane.prompt}
7360
+ ${footer}`:footer;return{...result,text,outputPreviewChars:text.length}}function parsePrReviewCollectionReceipt(record3){if(!record3.result)return null;let payload=parsePrReviewCollectionReceiptFooter(record3,record3.result);return payload?projectPrReviewCollectionReceipt(payload):null}function recordToLaneResult(record3,batchId,deliveryContext){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,digest5=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1,reviewReceipt=parsePrReviewCollectionReceipt(record3)??deliveryContext?.reviewReceipts?.get(record3.correlationId);if(record3.result?.text!==void 0&&status!=="pending"&&digest5&&outputRef){let key2=`${batchId}\x00${laneId}\x00${digest5}`;if(alreadyDelivered=hasLaneOutputBeenDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2),!alreadyDelivered)markLaneOutputDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2)}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.workflowLaneFailureClass!==void 0?{workflow_lane_failure_class:record3.result.workflowLaneFailureClass}:{},...record3.result.salvagedWorkflowLanes?.length?{salvaged_workflow_lanes:[...record3.result.salvagedWorkflowLanes]}:{},...record3.result.salvagedWorkflowLaneRecoveries?.length?{salvaged_workflow_lane_recoveries:record3.result.salvagedWorkflowLaneRecoveries.map((recovery)=>({workflow_lane:recovery.workflowLane,kind:recovery.kind,reason:recovery.reason}))}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{},...reviewReceipt?{accepted_review_item_ids:[...reviewReceipt.acceptedReviewItemIds],rejected_review_item_ids:[...reviewReceipt.rejectedReviewItemIds]}:{}}}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=_internals249.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`};if(generatedAgentNames.length>0){let normalized=agent.toLowerCase();if(!generatedAgentNames.find((name)=>name.toLowerCase()===normalized)){let shown=generatedAgentNames.slice(0,8).join(", "),overflow=generatedAgentNames.length>8?`, and ${generatedAgentNames.length-8} more`:"";return{ok:!1,role,error:`Agent "${agent}" is not registered on this host. Registered generated agent names: ${shown}${overflow}. Use a registered name (bare canonical roles are only valid when the host registers them).`}}}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(mode){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;if(tools.write=!1,tools.edit=!1,tools.patch=!1,mode==="swarm-pr-review:base"||mode==="swarm-pr-review:micro")for(let toolName of PR_REVIEW_CHILD_AGENT_TOOL_MAP.explorer??[])tools[toolName]=!0;return 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}}var ORIENTATION_SUFFIX_RESERVE_CHARS=5000;async function augmentCommonPromptWithOrientation(directory,lanes,commonPrompt,orientation,sessionID,deps){if(orientation===!1)return commonPrompt;let buildBlock=deps?.buildBlock??buildLaneOrientationBlock,block=null;try{block=await buildBlock(directory,lanes.map((lane)=>lane.prompt),sessionID?{sessionID}:void 0)}catch(error93){return log("lane orientation block failed open",{error:error93 instanceof Error?error93.message:String(error93)}),commonPrompt}if(!block)return commonPrompt;let combined=commonPrompt?`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${block}`:block;if(lanes.some((lane)=>combined.length+COMMON_PROMPT_SEPARATOR.length+lane.prompt.length+ORIENTATION_SUFFIX_RESERVE_CHARS>MAX_PROMPT_CHARS))return log("lane orientation block dropped: combined common_prompt + orientation + lane prompt + suffix reserve would exceed MAX_PROMPT_CHARS",{maxPromptChars:MAX_PROMPT_CHARS,blockChars:block.length}),commonPrompt;return combined}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=_internals249.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 isPrReviewDiscovery=options.mode==="swarm-pr-review:base"||options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer,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.",exactLaneInput=lane.workflow_lane??lane.id,exactLaneResult=classifyControllerTokenField(exactLaneInput);if(!exactLaneResult.ok){let reason=exactLaneResult.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" workflow_lane ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned,index)=>({index,result:classifyControllerTokenField(owned)})):[{index:0,result:exactLaneResult}],invalidOwnedLane=ownedLaneResults.find(({result})=>!result.ok);if(invalidOwnedLane){let reason=!invalidOwnedLane.result.ok&&invalidOwnedLane.result.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" owned_workflow_lanes[${invalidOwnedLane.index}] ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLanes=ownedLaneResults.map(({result})=>result.ok?result.token:""),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}if(isPrReviewDiscovery){let encouragesVerbatimShellQuoting=/(?:\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b.{0,80}\b(?:faithfully|verbatim|exactly|literally)\b|\b(?:faithfully|verbatim|exactly|literally)\b.{0,80}\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b)/i.test(lane.prompt),forbidden=[lane.prompt.includes(CANDIDATE_HEADERS.base_explorer)?"the canonical base discovery header":null,lane.prompt.includes(CANDIDATE_HEADERS.micro_lane)?"the canonical micro discovery header":null,/\[CANDIDATE\]/.test(lane.prompt)?"[CANDIDATE]":null,/\[CLEAN\]/.test(lane.prompt)?"[CLEAN]":null,encouragesVerbatimShellQuoting?"verbatim shell or pipeline quoting guidance":null].find((value)=>value!==null);if(forbidden)return errors5.push(`Lane "${lane.id}" operator prompt contains ${forbidden}; PR-review discovery prompts carry content only and the controller injects the authoritative output contract`),lane}let prompt=`${lane.prompt}
7361
7361
 
7362
7362
  ${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} (a repo-graph orientation block may have been prepended to common_prompt — retry with orientation: false to exclude it)`;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 prReviewLaneResponseBudgetChars(mode,lane){if(mode==="swarm-pr-review:base")return PR_REVIEW_BASE_LANE_RESPONSE_BUDGET_CHARS;if(mode==="swarm-pr-review:micro"){let owned=Math.max(1,lane.owned_workflow_lanes?.length??1);return Math.min(PR_REVIEW_RESPONSE_BUDGET_CEILING_CHARS,PR_REVIEW_MICRO_LANE_RESPONSE_BUDGET_CHARS+(owned-1)*PR_REVIEW_MICRO_PER_OWNED_LANE_CHARS)}if(mode==="swarm-pr-review:council")return PR_REVIEW_COUNCIL_LANE_RESPONSE_BUDGET_CHARS;if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let items=Math.max(0,lane.review_item_ids?.length??0);return Math.min(PR_REVIEW_RESPONSE_BUDGET_CEILING_CHARS,PR_REVIEW_VERDICT_RESPONSE_FLOOR_CHARS+items*PR_REVIEW_VERDICT_RESPONSE_PER_ITEM_CHARS)}return}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 normalizedMode=classifyControllerTokenField(mode),workflowLane=classifyControllerTokenField(lane.workflow_lane??""),prHeadSha=classifyControllerTokenField(options.prHeadSha??""),revisionDigest=classifyControllerTokenField(options.revisionDigest??""),batchId=classifyControllerTokenField(options.batchId??""),laneId=classifyControllerTokenField(lane.id),requiresSettlementProvenance=options.batchId!==void 0&&normalizedMode.ok&&(normalizedMode.token==="swarm-pr-review:base"||normalizedMode.token==="swarm-pr-review:micro"),declaredScope=canonicalizeControllerField(options.scope??"the exact checked-out PR revision and repository-defined diff context"),callerFocus=canonicalizeControllerField(options.callerFocus??""),assignedIdResults=(lane.review_item_ids??lane.feedback_item_ids??[]).map((itemId)=>classifyControllerTokenField(itemId)),invalidAssignedId=assignedIdResults.find((result)=>!result.ok);if(!normalizedMode.ok||!prHeadSha.ok||!revisionDigest.ok||requiresSettlementProvenance&&(!batchId.ok||!laneId.ok))return errors5.push(`Lane "${lane.id}" mandatory PR workflow contract requires non-empty single-token mode, pr_head_sha, revision_digest, and (for base/micro lanes) batch/lane provenance after controller sanitization`),lane;if(!workflowLane.ok&&workflowLane.reason==="multiple")return errors5.push(`Lane "${lane.id}" workflow_lane must be exactly one token after controller sanitization`),lane;if(invalidAssignedId)return errors5.push(`Lane "${lane.id}" assigned_item_ids must contain exactly one token per item after controller sanitization`),lane;let fallbackChecklist=normalizedMode.token.endsWith(":reviewer")?"re-read every assigned candidate at its exact location; prove classification, reachability, mitigation, severity, and falsification path":normalizedMode.token.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",ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned)=>classifyControllerTokenField(owned)):void 0;if(ownedLaneResults?.find((result)=>!result.ok))return errors5.push(`Lane "${lane.id}" owned_workflow_lanes must contain exactly one token per item after controller sanitization`),lane;let ownedLanes=ownedLaneResults?.map((result)=>result.ok?result.token:""),assignedIds=assignedIdResults.map((result)=>result.ok?result.token:""),checklist=ownedLanes?ownedLanes.map((owned)=>`[${owned}] ${PR_WORKFLOW_LANE_CHECKLISTS[owned]??fallbackChecklist}`).join(" "):PR_WORKFLOW_LANE_CHECKLISTS[workflowLane.ok?workflowLane.token:""]??fallbackChecklist,ownedLine=ownedLanes?`
7363
7363
  owned_workflow_lanes: ${ownedLanes.join(", ")} — every owned obligation requires its own [CANDIDATE] rows or fully populated [CLEAN] attestation naming that obligation`:"",responseBudget=prReviewLaneResponseBudgetChars(normalizedMode.token,lane),budgetLine=responseBudget!==void 0?`