opencode-swarm 7.139.1 → 7.139.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 (35) hide show
  1. package/.opencode/skills/swarm-pr-review/SKILL.md +15 -0
  2. package/dist/cli/{config-doctor-tgnr91q3.js → config-doctor-hrb61yqe.js} +2 -2
  3. package/dist/cli/{curation-policy-2qnhgdtt.js → curation-policy-4tp0mbcb.js} +2 -2
  4. package/dist/cli/{curator-llm-factory-1ftzece0.js → curator-llm-factory-hvw13hmr.js} +12 -12
  5. package/dist/cli/{curator-nbsag633.js → curator-vpcs1p1v.js} +12 -12
  6. package/dist/cli/{guardrail-explain-vb9k9zwm.js → guardrail-explain-k62h3c92.js} +13 -13
  7. package/dist/cli/{guardrail-log-0djnvfas.js → guardrail-log-2ftew0p3.js} +3 -3
  8. package/dist/cli/{hive-promoter-bpt26yew.js → hive-promoter-mpf0cfkk.js} +12 -12
  9. package/dist/cli/{index-xec724kg.js → index-3radty3f.js} +1 -1
  10. package/dist/cli/{index-hgrkhxbk.js → index-6c5f309q.js} +2 -2
  11. package/dist/cli/{index-0ymhx85c.js → index-6w1re1qn.js} +1 -1
  12. package/dist/cli/{index-hn0mdcmj.js → index-8gftfvpp.js} +1 -1
  13. package/dist/cli/{index-15526t16.js → index-8p9pasnp.js} +1 -1
  14. package/dist/cli/{index-xr07r80d.js → index-a7nh382r.js} +37 -36
  15. package/dist/cli/{index-db7wf6ke.js → index-cyw81ngh.js} +4 -4
  16. package/dist/cli/{index-aymt7hzw.js → index-e9tx99ds.js} +1 -1
  17. package/dist/cli/{index-ywysg26s.js → index-ffpmqx30.js} +2 -2
  18. package/dist/cli/{index-en6qq954.js → index-ktagrqxw.js} +3 -3
  19. package/dist/cli/{index-dw09fz3w.js → index-q11t5erh.js} +1 -1
  20. package/dist/cli/{index-xka8s8jw.js → index-se8xc78k.js} +14 -14
  21. package/dist/cli/{index-vxbppwvf.js → index-w71cq27a.js} +5 -5
  22. package/dist/cli/{index-91s653xx.js → index-y47dwge1.js} +1 -1
  23. package/dist/cli/{index-y1zcsf2a.js → index-y64jv2pe.js} +1 -1
  24. package/dist/cli/{index-ht4q3548.js → index-yr6x707c.js} +2 -2
  25. package/dist/cli/index.js +12 -12
  26. package/dist/cli/{knowledge-escalator-pjg2x75c.js → knowledge-escalator-n9pmx4qr.js} +3 -3
  27. package/dist/cli/{knowledge-events-vxheptk8.js → knowledge-events-raevm18w.js} +1 -1
  28. package/dist/cli/{knowledge-store-36mascwz.js → knowledge-store-bcfqz8fr.js} +1 -1
  29. package/dist/cli/{knowledge-validator-anats6rj.js → knowledge-validator-jxqj96cx.js} +4 -4
  30. package/dist/cli/{scan-cursor-apbz9eez.js → scan-cursor-ah5swtyh.js} +2 -2
  31. package/dist/cli/{schema-x9fr2ey8.js → schema-f7jgrtxj.js} +1 -1
  32. package/dist/cli/{skill-generator-20czn4kd.js → skill-generator-hp7as46c.js} +5 -5
  33. package/dist/hooks/pr-workflow-gate.d.ts +8 -1
  34. package/dist/index.js +4 -4
  35. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.139.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.139.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"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"preserve explicit dirty tracked files before an unbound PR workflow checkout with an auditable recovery receipt",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current plan: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan. Architect-only. Ratchet-tighter only — rejected once the profile is locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -183,7 +183,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
183
183
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=await runGitAsync(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
184
184
  `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolvePrFeedbackTrackingCandidatesAsync(directory,headSha){let[localOutput,remoteRefs]=await Promise.all([runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)%09%(upstream)","refs/heads"]),resolveRemoteRefsContainingHeadAsync(directory,headSha)]);if(localOutput===null||remoteRefs===null)return null;let exactRemoteRefs=new Set(remoteRefs);return{local:localOutput.split(/\r?\n/).map((line)=>line.trim().split("\t")).flatMap(([ref,objectName,upstream,...extras])=>{if(extras.length>0||!ref?.startsWith("refs/heads/")||objectName?.toLowerCase()!==headSha.toLowerCase()||!upstream?.startsWith("refs/remotes/")||!exactRemoteRefs.has(upstream))return[];return[{kind:"local",branchName:ref.slice(11),remoteTrackingRef:upstream}]}),remote:remoteRefs.map((remoteTrackingRef)=>({kind:"remote",remoteTrackingRef}))}}async function switchPrFeedbackTrackingCandidateAsync(directory,candidate){let args2=candidate.kind==="local"?["switch","--no-guess","--",candidate.branchName]:["switch","--track","--",candidate.remoteTrackingRef];return await runGitAsync(directory,args2)!==null}function revisionDigestGitCallFailure(call,result){let description=result.reason==="timeout"?"timed out":result.reason==="buffer-truncated"?"output exceeded the bounded buffer":"failed";return{ok:!1,reason:result.reason,detail:`git ${call} ${description}`}}function resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha){let projectRoot=path11.resolve(directory),baseHeadResult=runGitDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals7.gitTimeoutMs);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);let diffResult=runGitDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals7.revisionEnumerationTimeoutMs);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);let porcelainResult=runGitDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals7.revisionEnumerationTimeoutMs);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals7.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals7.revisionMaxFiles}`};let hash2=createHash7("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path11.resolve(projectRoot,relativePath),relativeToRoot=path11.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path11.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs7.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs7.readlinkSync(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals7.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals7.revisionMaxTotalBytes} at ${relativePath}`};try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(_internals7.readChangedFileSync(resolvedPath)),hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}}return{ok:!0,digest:hash2.digest("hex")}}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let result=resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);return result.ok?result.digest:null}async function resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha){let projectRoot=path11.resolve(directory),[baseHeadResult,diffResult,porcelainResult]=await Promise.all([runGitAsyncDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals7.gitTimeoutMs),runGitAsyncDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals7.revisionEnumerationTimeoutMs),runGitAsyncDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals7.revisionEnumerationTimeoutMs)]);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals7.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals7.revisionMaxFiles}`};let hash2=createHash7("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path11.resolve(projectRoot,relativePath),relativeToRoot=path11.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path11.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs7.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs7.promises.readlink(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals7.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals7.revisionMaxTotalBytes} at ${relativePath}`};hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs7.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return{ok:!1,reason:"read-failed",detail:`short read for ${relativePath}`};if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals7.yieldControl()}hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}finally{await handle?.close().catch(()=>{return})}}return{ok:!0,digest:hash2.digest("hex")}}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let result=await resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha);return result.ok?result.digest:null}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
185
185
  `).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oidMatch[1])&&oidMatch[1]!=="(initial)")return null;let gitHead=oidMatch[1]==="(initial)"?null:oidMatch[1],dirtyTrackedPaths=[],untrackedPaths=[],unmergedPaths=[],unmergedCodes=[],dirtySubmodulePaths=[],renameOrCopy=!1;for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){untrackedPaths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath||!fields[2])return null;if(dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("2 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath||!fields[2])return null;if(renameOrCopy=!0,dirtyTrackedPaths.push(changedPath,originalPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("u ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,10),unmergedCode=fields[1];if(!changedPath||!fields[2]||!unmergedCode||!/^(?:DD|AU|UD|UA|DU|AA|UU)$/.test(unmergedCode))return null;if(unmergedPaths.push(changedPath),unmergedCodes.push(unmergedCode),dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}return null}return{gitHead,dirtyTrackedPaths:[...new Set(dirtyTrackedPaths)],untrackedPaths:[...new Set(untrackedPaths)],renameOrCopy,unmergedPaths:[...new Set(unmergedPaths)],unmergedCodes:[...new Set(unmergedCodes)],dirtySubmodulePaths:[...new Set(dirtySubmodulePaths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0,upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelain=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:path11.resolve(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]:null,prHeadSha,scope}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(path11.resolve(expected.directory)!==path11.resolve(current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash7("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=33554432,REVISION_MAX_FILES=50000,REVISION_MAX_TOTAL_BYTES=536870912,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,REVISION_ENUMERATION_TIMEOUT_MS=15000,GITLINK_MODE_PATTERN,compareWorkspaceSnapshot,_internals7;var init_workspace_snapshot=__esm(()=>{init_bun_compat();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals7={spawnSync:child_process.spawnSync,bunSpawn,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve7)=>setImmediate(resolve7)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs7.readFileSync(filePath)}});import*as fs8 from"node:fs";import*as path12 from"node:path";function isExecutableFile(candidate){try{return fs8.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path12.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path12.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path12.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path12.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}async function readBoundedStream(stream,maxBytes){let reader=stream.getReader(),lockReleased=!1,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancelAndRelease=async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}};if(maxBytes<=0)return await cancelAndRelease(),{text:"",truncated:!0};let chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining)),total+=remaining;truncated=!0,await cancelAndRelease();break}chunks.push(value),total+=value.byteLength}}finally{releaseLock()}let out=new Uint8Array(total),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(out),truncated}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function killProcess(proc){try{proc?.kill(timeoutKillSignal(_internals8.platform()))}catch{}}async function runExternalTool(options){if(!path12.isAbsolute(options.cwd))return{status:"spawn-error",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool cwd must be absolute"};if(options.abortSignal?.aborted)return{status:"cancelled",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled before spawn"};let proc,timeoutHandle,abortListener,exitSettled=!1,settledExitCode=null;try{proc=_internals8.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:options.timeoutMs});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,{kind:"exit",exitCode}}),timeout=new Promise((resolve7)=>{timeoutHandle=setTimeout(()=>{if(exitSettled){resolve7({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}killProcess(proc),resolve7({kind:"timeout"})},options.timeoutMs)}),cancelled=new Promise((resolve7)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,killProcess(proc),resolve7({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),stdoutPromise=readBoundedStream(proc.stdout,options.maxStdoutBytes),stderrPromise=readBoundedStream(proc.stderr,options.maxStderrBytes),exitResult=await Promise.race([exitPromise,timeout,cancelled]);if(exitResult.kind==="timeout")return{status:"timeout",exitCode:proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1};if(exitResult.kind==="cancelled")return{status:"cancelled",exitCode:proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled"};let[stdout,stderr]=await Promise.all([stdoutPromise,stderrPromise]);return{status:"completed",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated}}catch(err){return{status:"spawn-error",exitCode:proc?.exitCode??null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:err instanceof Error?err.message:String(err)}}finally{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(proc)try{proc.kill()}catch{}}}var DEFAULT_WINDOWS_EXTENSIONS,_internals8;var init_external_tool_runner=__esm(()=>{init_bun_compat();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"];_internals8={bunSpawn,platform:()=>process.platform}});import*as fsp2 from"node:fs/promises";import*as path13 from"node:path";function boundPath(value){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>MAX_EVIDENCE_PATH_LENGTH?`${cleaned.slice(0,MAX_EVIDENCE_PATH_LENGTH)}...`:cleaned}function evidence(parsed,worktreeRoot,gitDir,operations,detail){let allPaths=parsed?[...parsed.unmergedPaths,...parsed.dirtySubmodulePaths,...parsed.dirtyTrackedPaths,...parsed.untrackedPaths]:[],uniquePaths=[...new Set(allPaths)].map(boundPath);return{worktreeRoot:worktreeRoot?boundPath(worktreeRoot):null,gitDir:gitDir?boundPath(gitDir):null,operations,unmergedCodes:parsed?[...new Set(parsed.unmergedCodes)].sort():[],paths:uniquePaths.slice(0,MAX_EVIDENCE_PATHS),trackedCount:parsed?.dirtyTrackedPaths.length??0,untrackedCount:parsed?.untrackedPaths.length??0,pathsTruncated:uniquePaths.length>MAX_EVIDENCE_PATHS,...detail?{detail}:{}}}async function runGitCapture(directory,args2){let result=await runExternalTool({executable:"git",args:[...args2],cwd:path13.resolve(directory),timeoutMs:GIT_TIMEOUT_MS,maxStdoutBytes:MAX_GIT_OUTPUT_BYTES,maxStderrBytes:65536});return{ok:result.status==="completed"&&result.exitCode===0&&!result.stdoutTruncated&&!result.stderrTruncated,stdout:result.stdout}}async function activeOperations(gitDir){return(await Promise.all(OPERATION_MARKERS.map(async([name,marker])=>{try{return await fsp2.lstat(path13.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals9.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals9.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals9.runGitCapture(directory,["rev-parse","--absolute-git-dir"])]);if(!statusResult.ok||!rootResult.ok||!gitDirResult.ok)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Confirm this is a readable Git worktree and resolve filesystem or Git errors before starting the PR workflow.",evidence:evidence(null,null,null,[],"required Git inspection failed")};let worktreeRoot=rootResult.stdout.trim(),gitDir=gitDirResult.stdout.trim(),parsed=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsed)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let operations;try{operations=await _internals9.activeOperations(path13.resolve(gitDir))}catch{return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the unreadable Git operation state before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot,gitDir,[],"Git operation markers could not be inspected")}}let stateEvidence=evidence(parsed,worktreeRoot,gitDir,operations);if(parsed.unmergedCodes.length>0)return{kind:"recovery-required",code:"UNMERGED_INDEX",retryable:!1,requiredAction:"Resolve or abort the current merge/rebase/cherry-pick/revert operation manually; conflicted index entries must never be stashed by PR workflow startup.",evidence:stateEvidence};if(operations.length>0)return{kind:"recovery-required",code:"GIT_OPERATION_IN_PROGRESS",retryable:!1,requiredAction:"Complete or abort the active Git operation manually before starting the PR workflow.",evidence:stateEvidence};if(parsed.dirtySubmodulePaths.length>0)return{kind:"recovery-required",code:"DIRTY_SUBMODULE",retryable:!1,requiredAction:"Resolve or preserve dirty submodule worktrees manually; the checkout-preparation stash cannot safely preserve them.",evidence:stateEvidence};if([...parsed.dirtyTrackedPaths,...parsed.untrackedPaths].find((candidate)=>candidate===".swarm"||candidate.startsWith(".swarm/")||candidate.startsWith(".swarm\\")))return{kind:"recovery-required",code:"SWARM_STATE_TRACKING_ERROR",retryable:!1,requiredAction:"Restore .swarm/ so it is git-excluded before starting the PR workflow; runtime state must not be treated as checkout dirt.",evidence:stateEvidence};if(parsed.dirtyTrackedPaths.length===0&&parsed.untrackedPaths.length===0)return{kind:"clean",code:"CLEAN",retryable:!0,requiredAction:"No checkout recovery is required.",evidence:stateEvidence};return{kind:"stashable",code:"STASHABLE_CHANGES",retryable:!0,requiredAction:"Run prepare_pr_workflow_checkout once to preserve the ordinary working-tree changes before checkout.",evidence:stateEvidence}}var GIT_TIMEOUT_MS=5000,MAX_GIT_OUTPUT_BYTES=524288,MAX_EVIDENCE_PATHS=20,MAX_EVIDENCE_PATH_LENGTH=240,OPERATION_MARKERS,_internals9;var init_pr_workflow_state=__esm(()=>{init_workspace_snapshot();init_external_tool_runner();OPERATION_MARKERS=[["merge","MERGE_HEAD"],["rebase-merge","rebase-merge"],["rebase-apply-or-am","rebase-apply"],["cherry-pick","CHERRY_PICK_HEAD"],["revert","REVERT_HEAD"],["bisect","BISECT_START"],["sequencer","sequencer"]];_internals9={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash8,randomUUID as randomUUID3}from"node:crypto";import{readFileSync as readFileSync6}from"node:fs";import*as fsp3 from"node:fs/promises";import*as path14 from"node:path";function computePrReviewDepthTier(stats2){if(!stats2)return"L";if(stats2.hasSubmoduleChange)return"L";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.smallMaxChangedFiles)return"S";if(stats2.changedLines<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedLines&&stats2.changedFiles<=PR_REVIEW_DEPTH_TIER_THRESHOLDS.mediumMaxChangedFiles)return"M";return"L"}function formatCheckoutRecoveryBlock(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),existing=await readPrWorkflowGateState(directory,normalizedSessionID);if(existing?.mode===mode){let activeState=existing;if(mode==="PR_FEEDBACK"&&options.prUrl){let requestedTarget=canonicalGitHubPrUrl(options.prUrl);if(!requestedTarget)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let existingTarget=existing.prFeedbackTargetUrl?canonicalGitHubPrUrl(existing.prFeedbackTargetUrl):null;if(existingTarget&&requestedTarget!==existingTarget)throw Error("BLOCKED: active PR_FEEDBACK targets a different GitHub pull request");if(!existingTarget)activeState={...existing,prFeedbackTargetUrl:options.prUrl,updatedAt:isoNow()},await persistState(directory,activeState)}return options.prHeadSha?bindPrWorkflowHead(directory,normalizedSessionID,options.prHeadSha):activeState}if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);if(options.requireCheckoutPreflight){let checkoutState=await classifyPrWorkflowGitState(directory);if(checkoutState.kind==="recovery-required"||checkoutState.kind==="indeterminate")throw Error(formatCheckoutRecoveryBlock(checkoutState))}let initialHead=options.prHeadSha?await assertCurrentCheckoutHead(directory,options.prHeadSha,mode):void 0,timestamp=isoNow(),feedbackTargetUrl=mode==="PR_FEEDBACK"&&options.prUrl?canonicalGitHubPrUrl(options.prUrl)?options.prUrl:null:void 0;if(feedbackTargetUrl===null)throw Error("BLOCKED: PR_FEEDBACK target must be a canonical GitHub PR URL");let nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:0,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode,activatedAt:timestamp,updatedAt:timestamp,...initialHead?{prHeadSha:initialHead}:{},...feedbackTargetUrl?{prFeedbackTargetUrl:feedbackTargetUrl}:{}};return await persistState(directory,nextState),nextState}async function readPrWorkflowGateState(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(state)rememberState(directory,state);else trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID));return state}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!current||current.revision!==expectedRevision)throw Error("BLOCKED: PR workflow gate state changed during terminal completion; revalidate the current session state before retrying")}try{await fsp3.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}trackedStatesByProjectSession.delete(stateCacheKey(directory,normalizedSessionID))})}async function abortPrWorkflow(directory,sessionID,options={}){let state=await requireAnyActiveState(directory,sessionID);if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,options.expectedMode);if(state.prFeedbackReadyToPublish)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting.`);let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0){let laneIds=openLanes.map((record2)=>record2.laneId??record2.subagentSessionId??"unknown").filter(Boolean).slice(0,10).join(", ");throw Error(`BLOCKED: ${state.mode} abort refused while ${openLanes.length} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`)}let sanitizedReason=typeof options.reason==="string"?options.reason.trim().slice(0,500):void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length,...sanitizedReason?{reason:sanitizedReason}:{}};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
186
- `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizeSessionID(sessionID));if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead,mode="PR_REVIEW"){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{commit}`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase()){let remediation=mode==="PR_FEEDBACK"?"Check out the intended local tracking branch at that exact head (for example with a safe standalone `gh pr checkout <number-or-url>` or `git switch -c <local> --track <remote>/<branch>`), then retry the bind. Do not create a new detached feedback checkout.":`Run these bare, standalone commands from that directory: if the commit is not present locally, \`git fetch origin <pr-head-ref>\`; then \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)throw Error(`BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful=new Set,dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful.add(obligation);for(let lane of batch.lanes){if((lane.ownedWorkflowLanes?.length??1)!==1)continue;let dimension=lane.ownedWorkflowLanes?.[0]??lane.workflowLane;if(batchSuccessful.has(dimension))dedicatedSuccessful.add(dimension)}let integrityPassingLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(integrityPassingLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0||!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful,dedicatedSuccessful,terminallyFailed}}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key){return key.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set2 of sets)for(let dimension of set2)if(!bitOf.has(dimension))bitOf.set(dimension,bitOf.size);let universeSize=bitOf.size;if(universeSize===0)return 0;let distinctMasks=new Set,largestSetSize=1;for(let set2 of sets){let mask=0,size=0;for(let dimension of set2){let bit=1<<bitOf.get(dimension);if((mask&bit)===0)size+=1;mask|=bit}if(mask===0)continue;distinctMasks.add(mask),largestSetSize=Math.max(largestSetSize,size)}if(universeSize>MAX_COVER_UNIVERSE_BITS)return Math.ceil(universeSize/largestSetSize);let full=(1<<universeSize)-1,unreachable=universeSize+1,best=Array(full+1).fill(unreachable);best[0]=0;for(let mask=0;mask<full;mask+=1){let steps=best[mask];if(steps===unreachable)continue;for(let setMask of distinctMasks){let next=mask|setMask;if(next===mask)continue;if(best[next]>steps+1)best[next]=steps+1}}return best[full]}function tierLBackingLaneCount(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key of state.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key),!0);for(let lane of normalizedLanes)considerLane(lane,!1);return{backingLanes:PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!consolidatedDimensions.has(dimension)).length+minimumConsolidatedLaneCover(consolidatedSets),consolidatedDimensions:[...consolidatedDimensions]}}async function tierLConsolidationRejection(directory,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest2=revisionDigest;if(!digest2)digest2=(await createPrReviewGateContext(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,digest2),consolidatedDimensions=[...new Set(consolidatedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]))].filter((dimension)=>Boolean(dimension)),alreadySuccessful=consolidatedDimensions.filter((dimension)=>attempts.successful.has(dimension));if(alreadySuccessful.length>0)return`These consolidated dimensions already have a successful source: ${alreadySuccessful.join(", ")}.`;let notTerminallyFailed=consolidatedDimensions.filter((dimension)=>!attempts.terminallyFailed.has(dimension));if(notTerminallyFailed.length>0)return`These consolidated dimensions have no recorded lane that reached a terminal non-successful state (never dispatched, still in flight, or awaiting ingestion): ${notTerminallyFailed.join(", ")}.`;let backing=tierLBackingLaneCount(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest2=revisionDigest??(await createPrReviewGateContext(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory(directory,state,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,state,{revisionDigest:digest2})},pruned=pruneWorkflowBatches(directory,state,digest2);if(!pruned)return state;let after={candidate:derivePrReviewCandidateInventory(directory,pruned,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,pruned,{revisionDigest:digest2})};if(!sameStringSet(before.candidate,after.candidate)||!sameStringSet(before.critic,after.critic))return warn("PR_REVIEW batch GC aborted: pruning would have changed the derived inventory; every batch was kept"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>successful.has(dimension))))contributingBaseBatchIds.add(batch.batchId)}let newestBaseBatchId=baseBatches.at(-1)?.batchId,survivingBase=baseBatches.filter((batch)=>batch.batchId===newestBaseBatchId||contributingBaseBatchIds.has(batch.batchId)),newestBatchIdByPhase=new Map;for(let batch of validationBatches)newestBatchIdByPhase.set(batch.phase,batch.batchId);let contributingReviewerBatchIds=new Set(composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state),covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}${malformedDiagnostics.length>0?`; first failed lane predicates: ${malformedDiagnostics.join(" | ")}`:""}; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; expected candidate row: ${CANDIDATE_HEADERS.base_explorer}; expected clean row: ${CLEAN_TEMPLATES.base_explorer}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),assertExactStringSet(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings}:{}};let nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext(directory,state),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow(state,requiredPhase);if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest2=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest2),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest2).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest2);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state,currentDigest),missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash8("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}function canonicalStageAObligation(obligation){return[obligation.id,obligation.category,obligation.workingDirectory,obligation.source,obligation.validatorContract?.path??"",obligation.validatorContract?.id??""].join("\x00")}function stageARetainsGateBatches(previous,next){if(!previous||previous.revisionDigest!==next.revisionDigest)return!1;if(!previous.applicableCategories||!previous.applicableObligations)return!1;let nextCategories=new Set(next.applicableCategories);if(!previous.applicableCategories.every((category)=>nextCategories.has(category)))return!1;let nextObligations=new Set(next.applicableObligations.map(canonicalStageAObligation));return previous.applicableObligations.every((obligation)=>nextObligations.has(canonicalStageAObligation(obligation)))}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch and the final receipt");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);let ctx=await createPrReviewGateContext(directory,state);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state,ctx),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let ctx=await createPrReviewGateContext(directory,state),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative4=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative4.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative4}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path14.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path14.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path14.relative(postRealRoot,postRealArtifact);if(postRootStat.isSymbolicLink()||!postRootStat.isDirectory()||!sameBigIntFileIdentity(rootStat,postRootStat)||postArtifactStat.isSymbolicLink()||!postArtifactStat.isFile()||!sameBigIntFileIdentity(artifactStat,postArtifactStat)||!sameBigIntFileIdentity(openedStat,postArtifactStat)||normalizeComparableFsPath(realRoot)!==normalizeComparableFsPath(postRealRoot)||normalizeComparableFsPath(realArtifact)!==normalizeComparableFsPath(postRealArtifact)||postRelativeRealPath===""||postRelativeRealPath===".."||postRelativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path14.normalize(path14.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash8("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash8("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: PR_REVIEW transition has ${open3.length} unsettled PR workflow lane(s)`);let ctx=await createPrReviewGateContext(directory,state);if(await assertPrReviewBaseCoverageSettled(directory,sessionID,ctx),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))detail="Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only.";else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest2?{ok:!0,digest:digest2}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifact(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function prReviewPhaseWindow(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane))}function composePrReviewPhaseVerdicts(directory,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],parsed=parseLaneItemVerdicts(artifact.text,declaredItems,phase,reviewerClaims);if(declaredItems.length>0&&parsed.size===declaredItems.length)satisfiedObligations.add(qualified.expectedWorkflowLane);for(let[itemId,verdict]of parsed){if(!requiredSet.has(itemId)||claims.has(itemId))continue;if(coherence&&!coherence.validatedInventory.includes(itemId))continue;if(phase==="critic"&&coherence&&!criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims))continue;claims.set(itemId,{batchId:batch.batchId,laneId:qualified.expectedLane.laneId,workflowLane:qualified.expectedWorkflowLane,...verdict}),contributed=!0}}if(contributed)contributingBatchIds.push(batch.batchId);if(!exhaustive&&claims.size===requiredSet.size)break}for(let obligation of new Set(scannedBatches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))){if(satisfiedObligations.has(obligation))continue;appendCompositionDiagnostic(diagnostics,`declared ${phase} lane "${obligation}" produced no successful exact artifact`)}let composition={claims,requiredInventory,unclaimed:requiredInventory.filter((itemId)=>!claims.has(itemId)),contributingBatchIds,diagnostics};if(!exhaustive)if(phase==="reviewer")ctx.reviewer=composition;else ctx.critic=composition;return composition}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bound=coherence.reviewerItemBindings?.[itemId],current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&&current&&bound===current)}function authoritativeReviewerClaims(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[itemId]=rowDigest}return bindings}function derivePrReviewCriticInventory(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0)return failedLaneValidation("result.transcript_incomplete","not true",!0);if(result?.truncated===!0)return failedLaneValidation("result.truncated","not true",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful=new Set;for(let qualified of recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics))if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful.add(obligation);return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic",parsed=parseLaneItemVerdicts(artifact.text,reviewItemIds??[],phase,reviewerClaims);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>parsed.has(itemId)))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifact(text,fallbackFamily),canonicalText=normalized.text,salvaged=normalized.synthesizedHeader,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,salvaged,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,salvaged,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,salvaged};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,salvaged};return{covered:!1,evidence:null,issues,salvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1});if(!recordIntegrity.ok)return recordIntegrity;let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode)})),salvagedLanes=[];for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;if(!analysis.salvaged&&analysis.issues.length===0)continue;salvagedLanes.push(workflowLane);let reason=analysis.salvaged?`canonical ${resolvePrReviewRowFamily(workflowLane,input.expected.mode)} header was absent and was synthesized from valid marker rows`:"one or more rows were dropped as malformed or out-of-ownership";warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}function parseReviewerVerdictFields(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return fields}function reviewerVerdictRowDigest(fields){return createHash8("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){let parsed=new Map;for(let itemId of itemIds){if(phase==="reviewer"){let fields=parseReviewerVerdictFields(text,itemId);if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let verdict=parseCriticVerdict(text,itemId,reviewerClaims?.get(itemId)?.severity);if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return parsed}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path14.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve9)=>{timeout=setTimeout(()=>{resolve9({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp3.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp3.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path14.normalize(path14.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash8("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path14.resolve(directory,".swarm"),parentPath=path14.dirname(path14.resolve(filePath)),relativeParent=path14.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path14.sep).filter(Boolean)){let nextPath=path14.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path14.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path14.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path14.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path14.dirname(filePath))]),relativeFile=path14.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID3()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve9)=>setTimeout(resolve9,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,TERMINAL_FAILED_DELEGATION_STATUSES,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_logger();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional()}).passthrough(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();TERMINAL_FAILED_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"]);PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS},beforeTerminalClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCandidateInventory(directory,state,ctx)},isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
186
+ `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,state.revision),{mode:state.mode,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},openLanes:openLanes.length}}async function bindPrWorkflowHead(directory,sessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state=await readPrWorkflowGateStateFromDisk(directory,normalizeSessionID(sessionID));if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState(directory,state),state}async function assertCurrentCheckoutHead(directory,expectedHead,mode="PR_REVIEW"){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error(`BLOCKED: cannot resolve the current Git HEAD in "${directory}" to verify against PR head "${normalizedExpected}". This means Git could not resolve HEAD (the working directory may not be a Git repository, HEAD may be unborn, the commit object may be missing in a shallow clone, the Git binary may not be on PATH, or the bounded Git invocation may have timed out). Verify with: git -C "${directory}" rev-parse --verify HEAD^{commit}`);if(currentHead.toLowerCase()!==normalizedExpected.toLowerCase()){let remediation=mode==="PR_FEEDBACK"?"Check out the intended local tracking branch at that exact head (for example with a safe standalone `gh pr checkout <number-or-url>` or `git switch -c <local> --track <remote>/<branch>`), then retry the bind. Do not create a new detached feedback checkout.":`Run these bare, standalone commands from that directory: if the commit is not present locally, \`git fetch origin <pr-head-ref>\`; then \`git switch --detach ${normalizedExpected}\`. Do not prefix the switch with \`git -C\`; the read-only shell classifier refuses \`git -C ... switch\`.`;throw Error(`BLOCKED: current checkout HEAD "${currentHead}" does not match PR head "${normalizedExpected}" (working directory: "${directory}"). ${remediation}`)}return normalizedExpected}async function assertPrReviewCleanCheckout(directory,mode="PR_REVIEW"){if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error(`BLOCKED: ${mode} requires a clean index and working tree at the exact PR head`)}async function assertPrFeedbackTrackingCheckout(directory,prHeadSha){let currentHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!currentHead)throw Error("BLOCKED: PR_FEEDBACK requires a resolved exact Git HEAD before first head bind");if(currentHead.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed before attach; expected ${prHeadSha}, received ${currentHead}`);let currentUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha);if(currentUpstream){if(matchingRemoteRefs===null)throw Error("BLOCKED: PR_FEEDBACK could not verify the current upstream against the exact intake PR head; the bounded Git query failed or timed out");if(matchingRemoteRefs.includes(currentUpstream.remoteTrackingRef))return;throw Error(`BLOCKED: PR_FEEDBACK current upstream "${currentUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}"; refusing to replace an existing tracking relationship`)}let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,prHeadSha);if(!candidates)throw Error(`BLOCKED: PR_FEEDBACK could not inspect tracked branches for exact PR head "${prHeadSha}"; the bounded Git query failed or timed out`);let{local:localCandidates,remote:remoteCandidates}=candidates;if(localCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,localCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact local tracked branch "${localCandidates[0].branchName}"; it may be checked out in another linked worktree or the bounded Git switch failed`)}else if(localCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple local tracked branches: ${localCandidates.map((candidate)=>candidate.branchName).join(", ")}`);else if(remoteCandidates.length===1){if(await _test_exports.beforePrFeedbackTrackingSwitch?.(),!await switchPrFeedbackTrackingCandidateAsync(directory,remoteCandidates[0]))throw Error(`BLOCKED: PR_FEEDBACK could not attach exact remote-tracking branch "${remoteCandidates[0].remoteTrackingRef}"; the bounded Git switch failed or timed out`)}else if(remoteCandidates.length>1)throw Error(`BLOCKED: PR_FEEDBACK exact head "${prHeadSha}" matches multiple remote-tracking refs: ${remoteCandidates.map((candidate)=>candidate.remoteTrackingRef).join(", ")}`);else throw Error("BLOCKED: PR_FEEDBACK requires a current local branch or exact remote-tracking ref that points to the intake PR head before the first bind");await _test_exports.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(attachedHead?.toLowerCase()!==prHeadSha.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK exact head changed after attach; expected ${prHeadSha}, received ${attachedHead??"(unresolved)"}`);if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,prHeadSha))?.includes(attachedUpstream.remoteTrackingRef))throw Error(`BLOCKED: PR_FEEDBACK upstream "${attachedUpstream.remoteTrackingRef}" must point to the exact intake PR head "${prHeadSha}" before the first head bind`)}async function enforcePrWorkflowDispatchLanesAsync(directory,sessionID,toolName){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]);if(claimedDimensionIds.filter((laneId)=>!PR_REVIEW_BASE_DIMENSION_IDS.includes(laneId)).length>0){let expected=PR_REVIEW_BASE_DIMENSION_IDS.join(", "),received=claimedDimensionIds.join(", ")||"(none)";throw Error(`BLOCKED: PR_REVIEW base dispatch lane ids must be drawn from: ${expected}. Received: ${received}`)}if((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)throw Error(`BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let record2={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2};return await persistState(directory,nextState),nextState}function summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest){let successful=new Set,dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful.add(obligation);for(let lane of batch.lanes){if((lane.ownedWorkflowLanes?.length??1)!==1)continue;let dimension=lane.ownedWorkflowLanes?.[0]??lane.workflowLane;if(batchSuccessful.has(dimension))dedicatedSuccessful.add(dimension)}let integrityPassingLaneIds=new Set(recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(integrityPassingLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0||!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.status)))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])terminallyFailed.add(dimension)}}return{successful,dedicatedSuccessful,terminallyFailed}}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key){return key.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set2 of sets)for(let dimension of set2)if(!bitOf.has(dimension))bitOf.set(dimension,bitOf.size);let universeSize=bitOf.size;if(universeSize===0)return 0;let distinctMasks=new Set,largestSetSize=1;for(let set2 of sets){let mask=0,size=0;for(let dimension of set2){let bit=1<<bitOf.get(dimension);if((mask&bit)===0)size+=1;mask|=bit}if(mask===0)continue;distinctMasks.add(mask),largestSetSize=Math.max(largestSetSize,size)}if(universeSize>MAX_COVER_UNIVERSE_BITS)return Math.ceil(universeSize/largestSetSize);let full=(1<<universeSize)-1,unreachable=universeSize+1,best=Array(full+1).fill(unreachable);best[0]=0;for(let mask=0;mask<full;mask+=1){let steps=best[mask];if(steps===unreachable)continue;for(let setMask of distinctMasks){let next=mask|setMask;if(next===mask)continue;if(best[next]>steps+1)best[next]=steps+1}}return best[full]}function tierLBackingLaneCount(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key of state.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key),!0);for(let lane of normalizedLanes)considerLane(lane,!1);return{backingLanes:PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!consolidatedDimensions.has(dimension)).length+minimumConsolidatedLaneCover(consolidatedSets),consolidatedDimensions:[...consolidatedDimensions]}}async function tierLConsolidationRejection(directory,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest2=revisionDigest;if(!digest2)digest2=(await createPrReviewGateContext(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,digest2),consolidatedDimensions=[...new Set(consolidatedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]))].filter((dimension)=>Boolean(dimension)),alreadySuccessful=consolidatedDimensions.filter((dimension)=>attempts.successful.has(dimension));if(alreadySuccessful.length>0)return`These consolidated dimensions already have a successful source: ${alreadySuccessful.join(", ")}.`;let notTerminallyFailed=consolidatedDimensions.filter((dimension)=>!attempts.terminallyFailed.has(dimension));if(notTerminallyFailed.length>0)return`These consolidated dimensions have no recorded lane that reached a terminal non-successful state (never dispatched, still in flight, or awaiting ingestion): ${notTerminallyFailed.join(", ")}.`;let backing=tierLBackingLaneCount(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest2=revisionDigest??(await createPrReviewGateContext(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory(directory,state,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,state,{revisionDigest:digest2})},pruned=pruneWorkflowBatches(directory,state,digest2);if(!pruned)return state;let after={candidate:derivePrReviewCandidateInventory(directory,pruned,{revisionDigest:digest2}),critic:derivePrReviewCriticInventory(directory,pruned,{revisionDigest:digest2})};if(!sameStringSet(before.candidate,after.candidate)||!sameStringSet(before.critic,after.critic))return warn("PR_REVIEW batch GC aborted: pruning would have changed the derived inventory; every batch was kept"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>successful.has(dimension))))contributingBaseBatchIds.add(batch.batchId)}let newestBaseBatchId=baseBatches.at(-1)?.batchId,survivingBase=baseBatches.filter((batch)=>batch.batchId===newestBaseBatchId||contributingBaseBatchIds.has(batch.batchId)),newestBatchIdByPhase=new Map;for(let batch of validationBatches)newestBatchIdByPhase.set(batch.phase,batch.batchId);let contributingReviewerBatchIds=new Set(composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),batches=state.prReviewBaseDispatches??[];if(batches.length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state),covered=new Set,malformedDiagnostics=[];for(let batch of batches){let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest,malformedDiagnostics);for(let obligation of successful)covered.add(obligation)}let missing=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!covered.has(dimension));if(missing.length>0||covered.size!==PR_REVIEW_BASE_DIMENSION_IDS.length)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete; missing dimensions: ${missing.join(", ")||"(none)"}${malformedDiagnostics.length>0?`; first failed lane predicates: ${malformedDiagnostics.join(" | ")}`:""}; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; expected candidate row: ${CANDIDATE_HEADERS.base_explorer}; expected clean row: ${CLEAN_TEMPLATES.base_explorer}`);return state}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),assertExactStringSet(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings}:{}};let nextState={...state,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record2],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext(directory,state),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow(state,requiredPhase);if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){if(!sameStringArray(state.prFeedbackInventory,normalizedInventory))throw Error("BLOCKED: PR_FEEDBACK inventory is immutable after declaration");return state}let nextState={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest2=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest2),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest2).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest2);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!feedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state,currentDigest),missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash8("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0};return await persistState(directory,nextState),nextState}function canonicalStageAObligation(obligation){return[obligation.id,obligation.category,obligation.workingDirectory,obligation.source,obligation.validatorContract?.path??"",obligation.validatorContract?.id??""].join("\x00")}function stageARetainsGateBatches(previous,next){if(!previous||previous.revisionDigest!==next.revisionDigest)return!1;if(!previous.applicableCategories||!previous.applicableObligations)return!1;let nextCategories=new Set(next.applicableCategories);if(!previous.applicableCategories.every((category)=>nextCategories.has(category)))return!1;let nextObligations=new Set(next.applicableObligations.map(canonicalStageAObligation));return previous.applicableObligations.every((obligation)=>nextObligations.has(canonicalStageAObligation(obligation)))}async function recordPrFeedbackGateBatch(directory,sessionID,phase,lane,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!successfulObligationsFromExactBatch(directory,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}async function assertPrFeedbackPublicationArmed(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),armed=state.prFeedbackReadyToPublish;if(!armed)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK changed after publication was armed; rerun Stage A and every independent gate");if((await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim()!==armed.localHead)throw Error("BLOCKED: PR_FEEDBACK current Git HEAD changed after publication was armed");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK working tree changed after publication was armed");let currentTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!currentTarget||currentTarget.remoteName!==armed.remoteName||currentTarget.remoteBranchRef!==armed.remoteBranchRef||currentTarget.remoteTrackingRef!==armed.remoteRef)throw Error("BLOCKED: PR_FEEDBACK upstream publication target changed after publication was armed");return state}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,runId,artifactPath){let state=await assertPrReviewBaseCoverageSettled(directory,sessionID),normalizedRunId=runId.trim();if(!normalizedRunId)throw Error("BLOCKED: PR_REVIEW trigger artifact run_id is required");let normalizedPath=artifactPath.trim();if(!normalizedPath)throw Error("BLOCKED: PR_REVIEW trigger artifact path is required");if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state.prReviewTriggerEvalRunId}"`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state.prReviewArtifactRunId}"`);let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await persistState(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state=await assertPrReviewBaseCoverageSettled(directory,sessionID);if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact");let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);let ctx=await createPrReviewGateContext(directory,state);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory(directory,state,ctx),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort()))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory`);return state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(boundary==="post_explorer"){for(let record2 of records)if(record2.status!=="PENDING"||record2.next_action!=="route_to_reviewer")throw Error(`BLOCKED: PR_REVIEW post_explorer record ${record2.finding_id} must remain PENDING and route_to_reviewer`);return}let ctx=await createPrReviewGateContext(directory,state),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} has no authoritative reviewer verdict`);if(record2.severity&&record2.severity!==reviewer.severity)throw Error(`BLOCKED: PR_REVIEW ${boundary} record ${record2.finding_id} severity differs from its reviewer verdict`);let requiresCritic=reviewer.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(reviewer.severity);if(boundary==="post_reviewer"){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(record2.status!==expectedStatus)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} status differs from its reviewer verdict`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_reviewer record ${record2.finding_id} action does not match reviewer disposition`);continue}if(!requiresCritic){let expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification,expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus||record2.next_action!==expectedAction)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} cannot override its non-critic reviewer disposition`);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} has no authoritative critic verdict`);if(record2.severity&&record2.severity!==critic.severity)throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} severity differs from its critic verdict`);if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED"||record2.next_action!=="suppress_with_reason")throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} must preserve the critic DISPROVED disposition`)}else if(record2.status!=="CONFIRMED"||!["report","handoff_to_feedback"].includes(record2.next_action))throw Error(`BLOCKED: PR_REVIEW post_critic record ${record2.finding_id} action does not match its critic verdict`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return await persistState(directory,nextState),nextState}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative4=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative4.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative4}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path14.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp3.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp3.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),relativeRealPath=path14.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports.beforeBoundedSwarmFileOpen?.();let handle=await fsp3.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp3.lstat(swarmRoot,{bigint:!0}),fsp3.lstat(absPath,{bigint:!0}),fsp3.realpath(swarmRoot),fsp3.realpath(absPath)]),postRelativeRealPath=path14.relative(postRealRoot,postRealArtifact);if(postRootStat.isSymbolicLink()||!postRootStat.isDirectory()||!sameBigIntFileIdentity(rootStat,postRootStat)||postArtifactStat.isSymbolicLink()||!postArtifactStat.isFile()||!sameBigIntFileIdentity(artifactStat,postArtifactStat)||!sameBigIntFileIdentity(openedStat,postArtifactStat)||normalizeComparableFsPath(realRoot)!==normalizeComparableFsPath(postRealRoot)||normalizeComparableFsPath(realArtifact)!==normalizeComparableFsPath(postRealArtifact)||postRelativeRealPath===""||postRelativeRealPath===".."||postRelativeRealPath.startsWith(`..${path14.sep}`)||path14.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path14.normalize(path14.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash8("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash8("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: PR_REVIEW transition has ${open3.length} unsettled PR workflow lane(s)`);let ctx=await createPrReviewGateContext(directory,state);if(await assertPrReviewBaseCoverageSettled(directory,sessionID,ctx),!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return state}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=await assertPrReviewTerminalReady(directory,normalizedSessionID);if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),sourceRevision=ready.revision,provenance="active-review-v1"}else{if(!request.prUrl)throw Error("BLOCKED: continuing a completed PR_REVIEW requires an explicit GitHub PR URL");sourceIdentity=`external-${preliminaryRead.digest.slice(0,32)}`,provenance="external-v1"}return await _test_exports.beforePrFeedbackTransitionLock?.(),withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID3(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})})}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID){let declaration=await resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId);if(!declaration)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),nextState={...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?{...entry,consumedByCallId:callID}:entry)};return await persistState(directory,nextState),{...declaration,consumedByCallId:callID}}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[]){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)return;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedRoles=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)).map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isNamedReadOnlyTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{}),isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool)&&readOnlyToolArgumentsAreSafe(args2??{});if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){if(!(isInternalWorkflowTool||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, verify the full commit object with `git cat-file -e <full_pr_head_sha>^{commit}`, then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID)).prFeedbackReadyToPublish;if(isSafeExactBoundPush(command,armed))return;throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha){let state=await requireBoundState(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let open3=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(open3.length>0)throw Error(`BLOCKED: ${expectedMode} completion has ${open3.length} unsettled PR workflow lane(s)`);if(expectedMode==="PR_REVIEW"){let readyState=await assertPrReviewTerminalReady(directory,sessionID);if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state")}else{let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let localHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");if(await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead)!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");return await persistState(directory,{...readyState,updatedAt:isoNow(),prFeedbackReadyToPublish:{revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,validatedAt:isoNow()}}),"ready-to-publish"}if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`)}return await _test_exports.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,state.revision),"completed"}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`);return state}async function requireBoundState(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds)assertNoDuplicates(reviewItemIds,"review item ids within one lane");let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function readOnlyToolArgumentsAreSafe(value,key="",depth=0){if(depth>8)return!1;let keyTokens=key.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return!1;if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim());if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim());if(/^mode$/i.test(key)&&typeof value==="string")return/^(?:r|rb|read)$/i.test(value.trim());if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return!1;return!/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return!0;if(Array.isArray(value))return value.every((entry)=>readOnlyToolArgumentsAreSafe(entry,key,depth+1));if(typeof value==="object")return Object.entries(value).every(([childKey,childValue])=>readOnlyToolArgumentsAreSafe(childValue,childKey,depth+1));return!1}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail;if(/[\r\n;&|<>`]/.test(inner)||/\$\(|@\(/.test(inner))detail="Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only.";else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function hasUnsafeShellControlSyntax(command){return/[;&|<>`\r\n]/.test(command)||/\$\(/.test(command)}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isSafeExactBoundPush(command,armed){if(hasUnsafeShellControlSyntax(command))return!1;let target=boundPushTarget(armed);if(!target)return!1;let match=command.trim().match(/^git\s+push\s+([^\s;&|<>`]+)\s+([^\s;&|<>`]+)\s*$/i);if(!match)return!1;return match[1]===target.remote&&match[2]===`${armed.localHead}:refs/heads/${target.branch}`}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest2=_test_exports.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest2?{ok:!0,digest:digest2}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}function assertExactStringSet(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),missing=[...expectedSet].filter((value)=>!actualSet.has(value)),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length!==actualSet.size||actualSet.size!==expectedSet.size||missing.length>0||extra.length>0)throw Error(`BLOCKED: ${label} must exactly cover the mechanically derived inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory(directory,state,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;if(!ownedDimensions.every((dimension)=>successful.has(dimension)))continue;let key=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key,ownedDimensions.length);for(let dimension of ownedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key))continue;seenBaseSourceKeys.add(key);let credited=baseSourceCreditedDimensions.get(key),fullOwnershipCount=baseSourceFullOwnershipCount.get(key)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{triggerArtifact=JSON.parse(readFileSync6(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id})}let candidateIds=[],extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.status!=="completed"||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha||record2.result?.outputDegraded===!0||record2.result?.transcriptIncomplete===!0||record2.result?.truncated===!0)continue;let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey))extractedLaneKeys.add(laneKey),candidateIds.push(...extractCandidateIds(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes))}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact)throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():["CLEAN-REVIEW"],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifact(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateIds(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane)).map((row)=>row.candidateId)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function prReviewPhaseWindow(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful.size===batch.lanes.length&&batch.lanes.every((lane)=>successful.has(lane.workflowLane))}function composePrReviewPhaseVerdicts(directory,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],parsed=parseLaneItemVerdicts(artifact.text,declaredItems,phase,reviewerClaims);if(declaredItems.length>0&&parsed.size===declaredItems.length)satisfiedObligations.add(qualified.expectedWorkflowLane);for(let[itemId,verdict]of parsed){if(!requiredSet.has(itemId)||claims.has(itemId))continue;if(coherence&&!coherence.validatedInventory.includes(itemId))continue;if(phase==="critic"&&coherence&&!criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims))continue;claims.set(itemId,{batchId:batch.batchId,laneId:qualified.expectedLane.laneId,workflowLane:qualified.expectedWorkflowLane,...verdict}),contributed=!0}}if(contributed)contributingBatchIds.push(batch.batchId);if(!exhaustive&&claims.size===requiredSet.size)break}for(let obligation of new Set(scannedBatches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))){if(satisfiedObligations.has(obligation))continue;appendCompositionDiagnostic(diagnostics,`declared ${phase} lane "${obligation}" produced no successful exact artifact`)}let composition={claims,requiredInventory,unclaimed:requiredInventory.filter((itemId)=>!claims.has(itemId)),contributingBatchIds,diagnostics};if(!exhaustive)if(phase==="reviewer")ctx.reviewer=composition;else ctx.critic=composition;return composition}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bound=coherence.reviewerItemBindings?.[itemId],current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&&current&&bound===current)}function authoritativeReviewerClaims(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[itemId]=rowDigest}return bindings}function derivePrReviewCriticInventory(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>verdict.classification==="CONFIRMED"&&["CRITICAL","HIGH","MEDIUM"].includes(verdict.severity)).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0)return failedLaneValidation("result.transcript_incomplete","not true",!0);if(result?.truncated===!0)return failedLaneValidation("result.truncated","not true",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful=new Set;for(let qualified of recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics))if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful.add(obligation);return successful}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic",parsed=parseLaneItemVerdicts(artifact.text,reviewItemIds??[],phase,reviewerClaims);return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>parsed.has(itemId)))}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>artifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifact(text,fallbackFamily),canonicalText=normalized.text,salvaged=normalized.synthesizedHeader,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,salvaged,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:!1,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,salvaged,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,salvaged};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,salvaged};return{covered:!1,evidence:null,issues,salvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1});if(!recordIntegrity.ok)return recordIntegrity;let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode)})),salvagedLanes=[];for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;if(!analysis.salvaged&&analysis.issues.length===0)continue;salvagedLanes.push(workflowLane);let reason=analysis.salvaged?`canonical ${resolvePrReviewRowFamily(workflowLane,input.expected.mode)} header was absent and was synthesized from valid marker rows`:"one or more rows were dropped as malformed or out-of-ownership";warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}function parseReviewerVerdictFields(text,itemId){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[REVIEWED]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==10||!fields.slice(1).every(Boolean))return null;let introduced=fields[5].replace(/^introduced_by_pr\s*:\s*/i,"").toUpperCase();if(!REVIEWER_CLASSIFICATIONS.has(fields[2])||!REVIEWER_EVIDENCE_TYPES.has(fields[3])||!REVIEW_SEVERITIES.has(fields[4])||!["YES","NO","UNKNOWN"].includes(introduced))return null;if(fields[7].length<8||fields[8].length<5||fields[9].length<3)return null;return fields}function reviewerVerdictRowDigest(fields){return createHash8("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){let parsed=new Map;for(let itemId of itemIds){if(phase==="reviewer"){let fields=parseReviewerVerdictFields(text,itemId);if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],rowDigest:reviewerVerdictRowDigest(fields)});continue}let verdict=parseCriticVerdict(text,itemId,reviewerClaims?.get(itemId)?.severity);if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return parsed}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields2)=>fields2[0]==="[CRITIC]"&&fields2[1]===itemId);if(rows.length!==1)return null;let fields=rows[0];if(fields.length!==6||!fields.slice(1).every(Boolean)||!CRITIC_STATUSES.has(fields[2])||!REVIEW_SEVERITIES.has(fields[3]))return null;if(fields[2]==="NEEDS_MORE_EVIDENCE")return null;if(fields[2]==="DISPROVED"&&fields[3]!=="NONE")return null;if(fields[2]==="UPHELD"&&!["CRITICAL","HIGH","MEDIUM"].includes(fields[3]))return null;if(fields[2]==="DOWNGRADED"&&fields[3]==="CRITICAL")return null;if(reviewerSeverity){let severityRank=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),reviewerRank=severityRank.get(reviewerSeverity),criticRank=severityRank.get(fields[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(fields[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(fields[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}if(fields[4].length<6||fields[5].length<6)return null;return{status:fields[2],severity:fields[3]}}function artifactHasExactPositiveVerdictRow(text,marker,itemId,positiveVerdict){let rows=text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]===marker&&fields[1]===itemId);return rows.length===1&&rows[0].length>=4&&rows[0][2]===positiveVerdict&&rows[0].slice(1,4).every(Boolean)}function pipeFields(line){if(!line.includes("|"))return[];return line.split("|").map((field)=>field.trim())}function feedbackArtifactCoversItems(directory,state,batchId,laneId,itemIds){let ref=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)return!1;let rows=loaded.artifact.text.split(/\r?\n/).map(pipeFields).filter((fields)=>fields[0]==="[FEEDBACK-VERIFIED]");if(rows.length!==itemIds.length)return!1;return itemIds.every((itemId)=>{let matches=rows.filter((fields)=>fields[1]===itemId);return matches.length===1&&matches[0].length===4&&matches[0].slice(1,4).every(Boolean)&&FEEDBACK_CLASSIFICATIONS.has(matches[0][2])})}async function persistState(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}async function writeStateWhileLocked(directory,state,options={}){let validated=PrWorkflowGateStateSchema.parse(state),current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=PrWorkflowGateStateSchema.parse({...validated,revision:validated.revision+1}),filePath=workflowGateStatePath(directory,validated.sessionID);return await writeAtomicJson2(directory,filePath,nextState),rememberState(directory,nextState),nextState}function workflowCheckoutMutationLockRelativePath(){return path14.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function openCheckoutLockFile(lockPath){return fsp3.open(lockPath,"wx")}function removeCheckoutLockFile(lockPath){return fsp3.rm(lockPath)}function checkoutMutationProjectKey(directory){return normalizeComparableFsPath(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve9)=>{timeout=setTimeout(()=>{resolve9({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},_test_exports.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key)===queued)pendingCheckoutMutationsByProject.delete(key)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await _test_exports.openCheckoutLock(lockPath),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(_test_exports.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await _test_exports.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await _test_exports.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key)??Promise.resolve(),release,current=new Promise((resolve9)=>{release=resolve9}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key)===queued)pendingStateMutationsByProjectSession.delete(key)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp3.open(lockPath,"wx"),lock={ownerToken:randomUUID3(),pid:process.pid,createdAtMs:_test_exports.nowMs()},writeError;try{await _test_exports.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(_test_exports.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat6=await fsp3.stat(lockPath);if(_test_exports.nowMs()-stat6.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp3.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp3.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp3.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function isProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}async function readPrWorkflowGateStateFromDisk(directory,sessionID){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp3.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return parsed.data}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function stateCacheKey(directory,sessionID){let resolved=path14.normalize(path14.resolve(directory));return`${process.platform==="win32"?resolved.toLowerCase():resolved}\x00${normalizeSessionID(sessionID)}`}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowGateStateLockRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path14.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest2=createHash8("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest2}`}function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}async function ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path14.resolve(directory,".swarm"),parentPath=path14.dirname(path14.resolve(filePath)),relativeParent=path14.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp3.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path14.sep).filter(Boolean)){let nextPath=path14.join(currentPath,segment);await _test_exports.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp3.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp3.realpath(currentPath),fsp3.realpath(nextPath)]);if(normalizeComparableFsPath(path14.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp3.realpath(swarmRoot),realParent=await fsp3.realpath(parentPath),relativeRealParent=path14.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat6=await fsp3.lstat(directoryPath,{bigint:!0});if(stat6.isSymbolicLink()||!stat6.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat6,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat6.dev,ino:stat6.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat6,realRoot,realFile,realParent]=await Promise.all([fsp3.lstat(filePath,{bigint:!0}),fsp3.realpath(path14.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path14.dirname(filePath))]),relativeFile=path14.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path14.sep}`)||path14.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID3()}`,tempIdentity,lastError;try{let handle=await fsp3.open(tempPath,"wx");try{await _test_exports.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await _test_exports.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await _test_exports.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS)}if(lastError)throw lastError;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp3.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve9)=>setTimeout(resolve9,ms))}var PR_REVIEW_BASE_DIMENSION_IDS,PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,GATE_SCHEMA_VERSION=1,MAX_TRACKED_SESSIONS=200,MAX_WORKFLOW_BATCHES=128,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",WORKFLOW_GATE_DIR="pr-workflow-gates",trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,TERMINAL_FAILED_DELEGATION_STATUSES,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_HANDOFF_MAX_BYTES=131072,PR_REVIEW_FINDINGS_MAX_BYTES=10485760,PrReviewFeedbackHandoffArtifactSchema,PrReviewFindingProjectionSchema,_test_exports,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,REVIEWER_CLASSIFICATIONS,REVIEWER_EVIDENCE_TYPES,REVIEW_SEVERITIES,CRITIC_STATUSES,FEEDBACK_CLASSIFICATIONS,PrWorkflowCheckoutMutationTimeoutError;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_pr_workflow_state();init_tool_metadata();init_logger();init_utils2();PR_REVIEW_BASE_DIMENSION_IDS=["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"],PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map,PrReviewBaseDimensionIdSchema=exports_external.enum(["intent-architecture","correctness-state","tests-falsifiability","security-trust","reliability-performance","compatibility-delivery"]),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8)}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional()}).passthrough(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewTriggerEvalRunId:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();TERMINAL_FAILED_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"]);PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();_test_exports={minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear(),_test_exports.beforeTerminalClear=void 0,_test_exports.beforePrFeedbackTransitionLock=void 0,_test_exports.beforePrFeedbackTrackingSwitch=void 0,_test_exports.afterPrFeedbackTrackingSwitch=void 0,_test_exports.beforePrFeedbackTrackingPersist=void 0,_test_exports.beforeBoundedSwarmFileOpen=void 0,_test_exports.beforeSessionStateLockWrite=void 0,_test_exports.beforeCheckoutLockWrite=void 0,_test_exports.beforeSafeDirectoryCreate=void 0,_test_exports.beforeAtomicTempWrite=void 0,_test_exports.beforeAtomicRename=void 0,_test_exports.openCheckoutLock=openCheckoutLockFile,_test_exports.removeCheckoutLock=removeCheckoutLockFile,_test_exports.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS},beforeTerminalClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:openCheckoutLockFile,removeCheckoutLock:removeCheckoutLockFile,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext(directory,state);return derivePrReviewCandidateInventory(directory,state,ctx)},isProcessAlive,isSafeStandaloneGitCommit,rename:fsp3.rename,nowMs:()=>Date.now()};PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;REVIEWER_CLASSIFICATIONS=new Set(["CONFIRMED","DISPROVED","UNVERIFIED","PRE_EXISTING"]),REVIEWER_EVIDENCE_TYPES=new Set(["STRUCTURALLY_PROVEN","EXECUTION_PROVEN","STATIC_TRACE_PROVEN","PLAUSIBLE_BUT_UNVERIFIED"]),REVIEW_SEVERITIES=new Set(["CRITICAL","HIGH","MEDIUM","LOW","INFO","NONE"]),CRITIC_STATUSES=new Set(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,reason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500)||void 0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
187
187
 
188
188
  ${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
189
189
 
@@ -6488,8 +6488,8 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
6488
6488
  `).trim(),text=bodyText.length>MAX_TEXT_LENGTH2?`${bodyText.slice(0,MAX_TEXT_LENGTH2)}…`:bodyText,textTruncated=outcome.truncated||bodyText.length>MAX_TEXT_LENGTH2,evidence2=await captureFetchEvidence(dirResult.directory,outcome.finalUrl,title,text),ok2={success:!0,url:parsed.data.url,finalUrl:outcome.finalUrl,status:outcome.status,contentType:outcome.contentType??void 0,title,text,truncated:textTruncated,bytesReturned:outcome.bytes.byteLength,evidence:evidence2};return JSON.stringify(ok2,null,2)}});async function captureFetchEvidence(directory,url3,title,text){try{let written=await _internals211.writeEvidenceDocuments(directory,[{sourceType:"crawl",url:url3,title,text,createdBy:"web_fetch"}]);return{stored:written.records.length>0,ref:written.refs[0],path:written.path}}catch(err2){return{stored:!1,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals211={httpRequest:performHttpRequest,dnsLookup:lookup,loadPluginConfig,writeEvidenceDocuments};init_zod();init_loader();var CURRENT_INTENT_RE=/\b(?:latest|current|currently|today|now|newest|recent|recently|up\s*-?\s*to\s*-?\s*date|this\s+(?:week|month|year)|as\s+of\s+(?:today|now))\b/i,HISTORICAL_INTENT_RE=/\b(?:history|historical|archive|archived|in\s+20\d{2}|during\s+20\d{2}|from\s+20\d{2}|for\s+20\d{2}|as\s+of\s+20\d{2})\b/i;function applySearchQueryPolicy(rawQuery,now=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now.getUTCFullYear(),temporalIntent=detectTemporalIntent(query),removedStaleYears=[];if(temporalIntent==="current")query=removeTrailingStaleCutoffYears(query,currentYear,removedStaleYears);return{originalQuery,query,temporalIntent,freshness:temporalIntent==="current"?chooseFreshness(query):void 0,removedStaleYears}}function detectTemporalIntent(query){if(CURRENT_INTENT_RE.test(query))return"current";if(HISTORICAL_INTENT_RE.test(query))return"historical";return"unspecified"}function chooseFreshness(query){if(/\b(?:today|now|as\s+of\s+(?:today|now))\b/i.test(query))return"day";if(/\bthis\s+week\b/i.test(query))return"week";if(/\b(?:recent|recently|this\s+month)\b/i.test(query))return"month";return"year"}function removeTrailingStaleCutoffYears(query,currentYear,removed){return query.replace(/\s+(?:as\s+of\s+)?(20\d{2})\s*$/i,(match,year)=>{if(Number(year)>=currentYear)return match;return removed.push(year),""}).replace(/\s+/g," ").trim()}class WebSearchError extends Error{cause;constructor(message,cause){super(message);this.cause=cause;this.name="WebSearchError"}}class WebSearchConfigError extends Error{constructor(message){super(message);this.name="WebSearchConfigError"}}class TavilyProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let requestBody={api_key:this.apiKey,query,max_results:maxResults,search_depth:"advanced"};if(options.freshness)requestBody.time_range=options.freshness;let response;try{response=await fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody)})}catch(err2){throw new WebSearchError(`Tavily network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Tavily HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Tavily returned non-JSON response",err2)}let results=body?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.content==="string").map((r)=>({title:r.title,url:r.url,snippet:r.content,query}))}}class BraveProvider{apiKey;constructor(apiKey){this.apiKey=apiKey}async search(query,maxResults,options={}){let url3=new URL("https://api.search.brave.com/res/v1/web/search");url3.searchParams.set("q",query),url3.searchParams.set("count",String(maxResults));let freshness=toBraveFreshness(options.freshness);if(freshness)url3.searchParams.set("freshness",freshness);let response;try{response=await fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"}})}catch(err2){throw new WebSearchError(`Brave network error for query "${query}"`,err2)}if(!response.ok)throw new WebSearchError(`Brave HTTP ${response.status} for query "${query}"`);let body;try{body=await response.json()}catch(err2){throw new WebSearchError("Brave returned non-JSON response",err2)}let results=body?.web?.results;if(!Array.isArray(results))return[];return results.filter((r)=>typeof r?.title==="string"&&typeof r?.url==="string"&&typeof r?.description==="string").map((r)=>({title:r.title,url:r.url,snippet:r.description,query}))}}function toBraveFreshness(freshness){switch(freshness){case"day":return"pd";case"week":return"pw";case"month":return"pm";case"year":return"py";default:return}}function resolveApiKey(provider,configKey){if(configKey&&configKey.length>0)return configKey;let envName=provider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY",fromEnv=process.env[envName];return fromEnv&&fromEnv.length>0?fromEnv:void 0}function createWebSearchProvider(config3){let apiKey=resolveApiKey(config3.searchProvider,config3.searchApiKey);if(!apiKey){let envName=config3.searchProvider==="tavily"?"TAVILY_API_KEY":"BRAVE_SEARCH_API_KEY";throw new WebSearchConfigError(`No API key for search provider "${config3.searchProvider}". Set council.general.searchApiKey in the resolved config (global ~/.config/opencode/opencode-swarm.json, project .opencode/opencode-swarm.json override) or export ${envName}.`)}switch(config3.searchProvider){case"tavily":return new TavilyProvider(apiKey);case"brave":return new BraveProvider(apiKey)}}init_create_tool();init_resolve_working_directory();var MAX_RESULTS_HARD_CAP=10,ArgsSchema7=exports_external.object({query:exports_external.string().min(1).max(500),max_results:exports_external.number().int().min(1).max(20).optional(),freshness:exports_external.enum(["auto","none","day","week","month","year"]).default("auto"),working_directory:exports_external.string().optional()}),web_search=createSwarmTool({description:"External web search for architect-driven council research, SME domain research, and skill-improver research. Returns titled results with snippets and URLs. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents and by SME to evaluate external skill/source candidates. Normalizes current-intent queries, strips trailing stale cutoff years, and applies provider freshness filters by default. Requires council.general.enabled and a configured search API key (Tavily or Brave) in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. max_results is capped at 10 with default from council.general.maxSourcesPerMember.",args:{query:exports_external.string().min(1).max(500).describe("Search query string (1–500 characters)."),freshness:exports_external.enum(["auto","none","day","week","month","year"]).optional().describe('Optional freshness filter. Query normalization always runs; "auto" infers provider freshness from current/recency terms, while "none" disables provider freshness filtering.'),max_results:exports_external.number().int().min(1).max(20).optional().describe(`Number of results to request (1–20). Hard-capped at ${MAX_RESULTS_HARD_CAP}. Defaults to council.general.maxSourcesPerMember.`),working_directory:exports_external.string().optional().describe("Project root for config resolution. Optional.")},execute:async(args2,directory)=>{let parsed=ArgsSchema7.safeParse(args2);if(!parsed.success){let fail={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail,null,2)}let generalConfig=loadPluginConfig(dirResult.directory).council?.general;if(!generalConfig||generalConfig.enabled!==!0)return JSON.stringify({success:!1,reason:"council_general_disabled",message:"web_search is disabled - set council.general.enabled: true in the resolved config: global ~/.config/opencode/opencode-swarm.json or project .opencode/opencode-swarm.json."},null,2);let requested=parsed.data.max_results??generalConfig.maxSourcesPerMember,maxResults=Math.min(requested,MAX_RESULTS_HARD_CAP),policy=applySearchQueryPolicy(parsed.data.query),requestedFreshness=parsed.data.freshness??"auto",freshness=requestedFreshness==="auto"?policy.freshness:requestedFreshness==="none"?void 0:requestedFreshness,provider;try{provider=createWebSearchProvider(generalConfig)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}try{let results=await provider.search(policy.query,maxResults,{freshness}),evidence2=await captureSearchEvidence(dirResult.directory,policy.query,results),scannedResults=results.map(({title,url:url3,snippet})=>{let titleScan=scanExternalContent(title,{trustLevel:"low"}),snippetScan=scanExternalContent(snippet,{trustLevel:"low"}),threatLevel=titleScan.threatLevel==="error"||snippetScan.threatLevel==="error"?"error":titleScan.threatLevel==="warning"||snippetScan.threatLevel==="warning"?"warning":"none";return{title:titleScan.clean?title:titleScan.neutralized,url:url3,snippet:snippetScan.clean?snippet:snippetScan.neutralized,evidenceRef:evidence2.refByUrl.get(url3),threatLevel}}),ok2={success:!0,query:policy.query,originalQuery:policy.originalQuery,temporalIntent:policy.temporalIntent,freshness,removedStaleYears:policy.removedStaleYears,totalResults:results.length,results:scannedResults,evidence:{stored:evidence2.stored,path:evidence2.path,refs:evidence2.refs,error:evidence2.error}};return JSON.stringify(ok2,null,2)}catch(err2){let fail={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals212.writeEvidenceDocuments(directory,results.map((result)=>({sourceType:"web_search",query,title:result.title,url:result.url,snippet:result.snippet,createdBy:"web_search"}))),refByUrl=new Map;for(let record3 of written.records)if(record3.url)refByUrl.set(record3.url,record3.ref);return{stored:written.records.length>0,path:written.path,refs:written.refs,refByUrl}}catch(err2){return{stored:!1,refs:[],refByUrl:new Map,error:err2 instanceof Error?err2.message:String(err2)}}}var _internals212={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store4();init_create_tool();init_resolve_working_directory();import*as path298 from"node:path";var FindingSchema3=exports_external.object({severity:exports_external.enum(["low","medium","high","critical"]),category:exports_external.string().min(1),agents:exports_external.array(exports_external.string().min(1)).default([]),tasks:exports_external.array(exports_external.string().min(1)).default([]),evidence_refs:exports_external.array(exports_external.string().min(1)).default([]),description:exports_external.string().min(1),recommendation:exports_external.string().default("")}),KnowledgeRecommendationSchema2=exports_external.object({lesson:exports_external.string().min(1),target_agents:exports_external.array(exports_external.string().min(1)).default([]),confidence:exports_external.number().min(0).max(1).default(0.5),evidence_refs:exports_external.array(exports_external.string().min(1)).default([])}),ArgsSchema8=exports_external.object({phase:exports_external.number().int().min(0).max(999),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),findings:exports_external.array(FindingSchema3).default([]),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).default([]),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional(),provenance_session_id:exports_external.string().min(1).optional()}),write_architecture_supervisor_evidence=createSwarmTool({description:"Persist the architecture supervisor verdict for a phase. PREREQUISITE: dispatch critic_architecture_supervisor as an Agent task with the phase + agent summaries, collect its strict-JSON verdict (verdict/findings/knowledge_recommendations), then call this tool with those values. Writes .swarm/evidence/{phase}/"+"architecture-supervisor.json. This tool persists only — it does not contact the "+"supervisor. Architect-only; config-gated via architectural_supervision.enabled.",args:{phase:exports_external.number().int().min(0).max(999).describe("Phase number being reviewed."),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]).describe("Supervisor verdict."),findings:exports_external.array(FindingSchema3).optional().describe("System-level findings from the supervisor."),knowledge_recommendations:exports_external.array(KnowledgeRecommendationSchema2).optional().describe("Durable lessons proposed by the supervisor."),working_directory:exports_external.string().optional(),provenance_agent_name:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)."),provenance_session_id:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance).")},execute:async(rawArgs,directory)=>{let parsed=ArgsSchema8.safeParse(rawArgs);if(!parsed.success)return JSON.stringify({success:!1,reason:"invalid arguments",errors:parsed.error.issues.map((i)=>({path:i.path.join("."),message:i.message}))},null,2);let args2=parsed.data,dirResult=resolveWorkingDirectory(args2.working_directory,directory);if(!dirResult.success)return JSON.stringify({success:!1,reason:dirResult.message},null,2);let provenance=args2.provenance_agent_name||args2.provenance_session_id?{agent_name:args2.provenance_agent_name,session_id:args2.provenance_session_id,captured_at:new Date().toISOString()}:void 0,report={schema_version:SUMMARY_SCHEMA_VERSION,phase:args2.phase,verdict:args2.verdict,findings:args2.findings,knowledge_recommendations:args2.knowledge_recommendations,created_at:new Date().toISOString(),...provenance?{provenance}:{}},evidencePath=writeSupervisorReport(dirResult.directory,report),knowledgeProposed=0,knowledgeReinforced=0,knowledgeQuarantined=0;try{let config3=loadPluginConfig(dirResult.directory);if(config3.architectural_supervision?.persist_knowledge_recommendations&&args2.knowledge_recommendations.length>0){let knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{}),lessons=args2.knowledge_recommendations.map((r)=>r.lesson),result=await curateAndStoreSwarm(lessons,path298.basename(dirResult.directory),{phase_number:args2.phase},dirResult.directory,knowledgeConfig,{skipAutoPromotion:!0,llmDelegate:createCuratorLLMDelegate(dirResult.directory,"phase"),enrichmentQuota:{maxCalls:knowledgeConfig.enrichment.max_calls_per_day,window:knowledgeConfig.enrichment.quota_window}});knowledgeProposed=result.stored,knowledgeReinforced=result.reinforced,knowledgeQuarantined=result.quarantined}}catch{}let skillsProposed=0;try{let config3=loadPluginConfig(dirResult.directory),hasFailureLoop=args2.findings.some((f)=>f.category==="failure_loop");if(config3.architectural_supervision?.persist_knowledge_recommendations&&hasFailureLoop)skillsProposed=(await generateSkills({directory:dirResult.directory,mode:"draft"})).written.length}catch{}return JSON.stringify({success:!0,phase:args2.phase,verdict:args2.verdict,findings_count:args2.findings.length,knowledge_proposed:knowledgeProposed,knowledge_reinforced:knowledgeReinforced,knowledge_quarantined:knowledgeQuarantined,skills_proposed:skillsProposed,evidence_path:evidencePath},null,2)}});init_zod();init_qa_gate_profile();import fs178 from"node:fs";import path299 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals213.normalizeVerdict2(args2.verdict),provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path299.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path299.dirname(validatedPath);try{await fs178.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path299.join(evidenceDir,`.${filename}.tmp`);await fs178.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs178.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath);let snapshotInfo,snapshotError,qaProfileLocked,qaProfileLockError;if(normalizedVerdict==="approved")try{let currentPlan=await loadPlanJsonOnly(directory);if(currentPlan){let snapshotEvent=await takeSnapshotEvent(directory,currentPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString()}});snapshotInfo={seq:snapshotEvent.seq,timestamp:snapshotEvent.timestamp};try{let planId=derivePlanId(currentPlan),locked=lockProfile(directory,planId,snapshotEvent.seq);qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(lockErr){let msg=lockErr instanceof Error?lockErr.message:String(lockErr);if(!/No QA gate profile/i.test(msg))qaProfileLockError=msg,log("[write_drift_evidence] QA gate profile lock failed:",msg)}}else snapshotError="plan.json not available for snapshot"}catch(err2){snapshotError=err2 instanceof Error?err2.message:String(err2),log("[write_drift_evidence] critic-approved snapshot failed:",snapshotError)}return JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,snapshotError,qaProfileLocked,qaProfileLockError},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals213={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_drift_evidence=createSwarmTool({description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();import fs179 from"node:fs";import path300 from"node:path";init_lock();init_utils2();init_config2();init_gateway();init_reward_capture();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();var FINAL_COUNCIL_MEMBERS=["critic","reviewer","sme","test_engineer","explorer"],VerdictSchema3=exports_external.object({agent:exports_external.enum(FINAL_COUNCIL_MEMBERS),verdict:exports_external.enum(["APPROVE","CONCERNS","REJECT"]),confidence:exports_external.number().min(0).max(1),findings:exports_external.array(exports_external.object({severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]),category:exports_external.string().min(1),location:exports_external.string(),detail:exports_external.string(),evidence:exports_external.string()})),criteriaAssessed:exports_external.array(exports_external.string()),criteriaUnmet:exports_external.array(exports_external.string()),durationMs:exports_external.number().nonnegative()}),ArgsSchema9=exports_external.object({phase:exports_external.number().int().min(1).max(1000),projectSummary:exports_external.string().min(1),roundNumber:exports_external.number().int().min(1).max(10).optional(),verdicts:exports_external.array(VerdictSchema3).min(1).max(5)});function normalizeFinalVerdict(verdict,requiredFixesCount){if(verdict==="APPROVE")return"approved";if(verdict==="REJECT")return"rejected";return requiredFixesCount>0?"rejected":"concerns"}function invalidResponse3(issues){return JSON.stringify({success:!1,reason:"invalid arguments",errors:issues.map((issue3)=>({path:issue3.path.join("."),message:issue3.message}))},null,2)}async function executeWriteFinalCouncilEvidence(args2,directory,ctx){let parsed=ArgsSchema9.safeParse(args2);if(!parsed.success)return await recordUnscopedCouncilAttempt(directory,"final","invalid_arguments",args2,parsed.error.issues.map((issue3)=>({path:issue3.path,code:issue3.code})),ctx?.sessionID)??invalidResponse3(parsed.error.issues);let input=parsed.data,config3=loadPluginConfig(directory),plan=null;try{plan=await loadPlan(directory)}catch{}let planHash=plan?computePlanHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,membersVoted=[...new Set(input.verdicts.map((v)=>v.agent))],membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!membersVoted.includes(member));return runCouncilAttempt({directory,scope:{kind:"final",generation:planHash??"missing-plan"},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,request:input,verdictCount:input.verdicts.length,members:membersVoted,probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<FINAL_COUNCIL_MEMBERS.length)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${FINAL_COUNCIL_MEMBERS.length} required members provided verdicts. Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}]. Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.`,membersVoted,membersAbsent,quorumRequired:FINAL_COUNCIL_MEMBERS.length},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),input.verdicts,authoritativeRound,config3.council);if(synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount>0)return{disposition:"blocking_concerns_unresolved",response:{success:!1,reason:"blocking_concerns_unresolved",overallVerdict:synthesis.overallVerdict,blockingConcernsCount:synthesis.blockingConcernsCount,requiredFixes:synthesis.requiredFixes,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:`Final council returned CONCERNS with ${synthesis.blockingConcernsCount} HIGH/CRITICAL finding(s) promoted to requiredFixes. These must be resolved before the project can close. Do NOT write evidence or proceed — address every requiredFix and resubmit.`},transition:"advance",gateEffect:"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize};if(!plan)return{disposition:"plan_not_found",response:{success:!1,reason:"plan_not_found",message:"Cannot write final council evidence: plan.json not found. The plan must be loaded and available before writing final council evidence.",phase:input.phase,plan_id:"unknown"},transition:"stay",gateEffect:"none"};let normalizedVerdict=normalizeFinalVerdict(synthesis.overallVerdict,synthesis.requiredFixes.length),evidenceEntry={type:"final-council",phase:input.phase,plan_id:planId,plan_hash:planHash,plan_identity_hash:planIdentityHash,verdict:normalizedVerdict,rawCouncilVerdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,membersVoted,membersAbsent,requiredFixes:synthesis.requiredFixes,advisoryFindings:synthesis.advisoryFindings,advisoryNotes:synthesis.advisoryNotes,unresolvedConflicts:synthesis.unresolvedConflicts,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,memberVerdicts:synthesis.memberVerdicts,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,projectSummary:synthesis.projectSummary,timestamp:synthesis.timestamp},validatedPath;try{validatedPath=_internals214.validateSwarmPath(directory,path300.join("evidence","final-council.json"))}catch(error93){return{disposition:"invalid_evidence_path",response:{success:!1,phase:input.phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},transition:"stay",gateEffect:"none"}}let evidenceDir=path300.dirname(validatedPath),accepted=synthesis.overallVerdict==="APPROVE"||synthesis.overallVerdict==="CONCERNS"&&synthesis.blockingConcernsCount===0;return{disposition:`evaluated_${synthesis.overallVerdict.toLowerCase()}`,response:{success:!0,phase:input.phase,overallVerdict:synthesis.overallVerdict,verdict:normalizedVerdict,vetoedBy:synthesis.vetoedBy,roundNumber:synthesis.roundNumber,allCriteriaMet:synthesis.allCriteriaMet,requiredFixesCount:synthesis.requiredFixes.length,advisoryFindingsCount:synthesis.advisoryFindings.length,unresolvedConflictsCount:synthesis.unresolvedConflicts.length,advisoryNotes:synthesis.advisoryNotes,membersVoted,membersAbsent,quorumSize:synthesis.quorumSize,quorumMet:!0,evidencePath:synthesis.evidencePath,unifiedFeedbackMd:synthesis.unifiedFeedbackMd,message:"Final council evidence written to .swarm/evidence/final-council.json"},transition:accepted?"close":"advance",gateEffect:accepted?"allowed":"blocked",verdict:synthesis.overallVerdict,quorumSize:synthesis.quorumSize,evidence:{reference:synthesis.evidencePath,commit:async(attemptId)=>{await withEvidenceLock(directory,path300.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computePlanHash(currentPlan)!==planHash)throw Error("final council plan changed before evidence publication");await fs179.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path300.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs179.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs179.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs179.promises.rm(tempPath,{force:!0}).catch(()=>{})}})}},afterCommit:async()=>{try{let memoryConfig=config3.memory;if(memoryConfig?.enabled===!0&&ctx?.sessionID){let provider=createConfiguredMemoryProvider(directory,memoryConfig);try{await applyCouncilReward(provider,{runId:ctx.sessionID,unitId:void 0,reward:COUNCIL_VERDICT_REWARDS[synthesis.overallVerdict],eta:memoryConfig.qLearning.learningRate,initialQValue:memoryConfig.qLearning.initialQValue,qLearning:memoryConfig.qLearning,timestamp:new Date().toISOString(),verdictLabel:synthesis.overallVerdict})}finally{await provider.close?.()}}}catch(rewardErr){warn(`[write-final-council-evidence] final council reward capture failed: ${rewardErr instanceof Error?rewardErr.message:String(rewardErr)}`)}}}}})}var write_final_council_evidence=createSwarmTool({description:"Write final council evidence for a completed project. This is not General Council mode and does not use convene_general_council. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks, collect their CouncilMemberVerdict JSON, then call this tool to synthesize and persist .swarm/evidence/final-council.json.",args:{phase:exports_external.number().int().min(1).max(1000).describe("The final phase number for the project being reviewed"),projectSummary:exports_external.string().min(1).describe("Summary of the completed project and total work reviewed"),roundNumber:exports_external.number().int().min(1).max(10).optional().describe("1-indexed final council round number. Defaults to the current server round."),verdicts:exports_external.array(VerdictSchema3).min(1).max(5).describe("Collected CouncilMemberVerdict objects from critic, reviewer, sme, test_engineer, and explorer.")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path300.join("evidence","final-council.json")),parsed=JSON.parse(fs179.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals214={validateSwarmPath};init_zod();import fs180 from"node:fs";import path301 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteHallucinationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals215.normalizeVerdict2(args2.verdict),evidenceContent={entries:[{type:"hallucination-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),findings:args2.findings}]},filename="hallucination-guard.json",relativePath2=path301.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path301.dirname(validatedPath);try{await fs180.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path301.join(evidenceDir,`.${filename}.tmp`);return await fs180.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs180.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Hallucination evidence written to .swarm/evidence/${phase}/hallucination-guard.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals215={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({description:"Write hallucination verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/hallucination-guard.json. Use this after critic_hallucination_verifier delegation to persist the verification result. Unlike write_drift_evidence, this tool does NOT lock the QA gate profile.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the hallucination verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the hallucination verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the hallucination verification"),findings:exports_external.string().optional().describe("Optional bullet list of FABRICATED/DRIFTED/UNSUPPORTED/BROKEN findings (for NEEDS_REVISION)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),findings:args2.findings!==void 0?String(args2.findings):void 0};return await executeWriteHallucinationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();import fs181 from"node:fs";import path302 from"node:path";init_utils2();init_swarm_artifact_cache();init_create_tool();async function executeWriteMutationEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict4(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP'"},null,2);if(args2.killRate!==void 0){if(typeof args2.killRate!=="number"||Number.isNaN(args2.killRate))return JSON.stringify({success:!1,phase,message:"Invalid killRate: must be a number"},null,2)}if(args2.adjustedKillRate!==void 0){if(typeof args2.adjustedKillRate!=="number"||Number.isNaN(args2.adjustedKillRate))return JSON.stringify({success:!1,phase,message:"Invalid adjustedKillRate: must be a number"},null,2)}let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals216.normalizeVerdict4(args2.verdict),evidenceEntry={type:"mutation-gate",verdict:normalizedVerdict,killRate:args2.killRate??0,adjustedKillRate:args2.adjustedKillRate??0,summary:summary.trim(),timestamp:new Date().toISOString()};if(args2.survivedMutants!==void 0)evidenceEntry.survivedMutants=args2.survivedMutants;let evidenceContent={entries:[evidenceEntry]},filename="mutation-gate.json",relativePath2=path302.join("evidence",String(phase),filename),validatedPath;try{validatedPath=validateSwarmPath(directory,relativePath2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:"Failed to validate path"},null,2)}let evidenceDir=path302.dirname(validatedPath);try{await fs181.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path302.join(evidenceDir,`.${filename}.tmp`);return await fs181.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs181.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Mutation gate evidence written to .swarm/evidence/${phase}/mutation-gate.json`},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals216={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID26}from"node:crypto";import*as fs182 from"node:fs";import*as path303 from"node:path";var RunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),FindingSchema4=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"]),severity:exports_external.enum(["CRITICAL","HIGH","MEDIUM","LOW"]).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),HandoffSchema=exports_external.object({pr_url:exports_external.string().url(),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),records:exports_external.array(FindingSchema4).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:HandoffSchema}).strict()]);function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{let stat19=await fs182.promises.stat(filePath);if(!stat19.isFile()||stat19.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs182.promises.readFile(filePath,"utf8")).split(/\r?\n/).filter(Boolean).map((line)=>JSON.parse(line))}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function atomicWrite6(filePath,content){await fs182.promises.mkdir(path303.dirname(filePath),{recursive:!0});let tempPath=path303.join(path303.dirname(filePath),`.${path303.basename(filePath)}.${randomUUID26()}.tmp`);try{await fs182.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs182.promises.rename(tempPath,filePath)}finally{await fs182.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3("PR-review artifact requires an active session");let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_REVIEW"||!state.prHeadSha)return failure3("PR-review artifact requires an active, bound PR_REVIEW gate");if(state.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(`PR-review artifact head mismatch: expected ${state.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==parsed.data.run_id)return failure3(`PR-review artifacts are already bound to run ${state.prReviewArtifactRunId}`);let relativeFindingsPath=path303.join("pr-review",parsed.data.run_id,"findings.jsonl"),findingsPath=validateSwarmPath(directory,relativeFindingsPath),existing=await readFindings(findingsPath);if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id);await assertPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,findingIds),await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records);let recordedAt=new Date().toISOString(),appended=findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended];await atomicWrite6(findingsPath,allRecords.map((record3)=>JSON.stringify(record3)).join(`
6489
6489
  `)+(allRecords.length>0?`
6490
6490
  `:""));let handoffRequired=[...latestFindings(allRecords).values()].some((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback");return await markPrReviewArtifactBoundary(directory,sessionID,findingsInput.run_id,findingsInput.boundary,relativeFindingsPath.split(path303.sep).join("/"),findingIds,handoffRequired),JSON.stringify({success:!0,path:relativeFindingsPath.split(path303.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,handoff_required:handoffRequired},null,2)}let actionableIds=[...latestFindings(existing).values()].filter((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback").map((record3)=>record3.finding_id).sort(),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`handoff finding_ids must exactly match actionable findings: ${actionableIds.join(", ")||"(none)"}`);let relativeHandoffPath=path303.join("pr-review",parsed.data.run_id,"feedback-handoff.json"),handoffPath=validateSwarmPath(directory,relativeHandoffPath);return await atomicWrite6(handoffPath,`${JSON.stringify({schema_version:1,run_id:parsed.data.run_id,pr_head_sha:state.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},null,2)}
6491
- `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path303.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path303.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(FindingSchema4).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID27}from"node:crypto";import fs183 from"node:fs";import path304 from"node:path";var _internals217={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals217.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals217.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals217.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(`PR_REVIEW trigger evaluation head mismatch: expected ${gateState.prHeadSha}, received ${parsed.data.pr_head_sha}`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigest(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4("Active PR_REVIEW trigger evaluation could not bind the current exact revision digest");let citedLaneOwnership=new Map;for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||record3.status!=="completed"||record3.result?.outputDegraded===!0||record3.result?.transcriptIncomplete===!0||record3.result?.truncated===!0||(record3.result?.chars??0)<=0||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||!recordOwnedLanes.every((ownedFamily)=>prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,ownedFamily,recordOwnedLanes,record3.mode))||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a completed non-degraded micro-lane artifact`)}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");let resolvedMergeBase=_internals217.resolveMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedMergeBase)return failure4("Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref and pr_head_sha");if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let artifact=buildPrReviewTriggerReceiptV2({run_id:parsed.data.run_id,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows}),relativePath2=path304.join("pr-review",parsed.data.run_id,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parent=path304.dirname(destination),tempPath=path304.join(parent,`.trigger-eval.${randomUUID27()}.tmp`);try{await fs183.promises.mkdir(parent,{recursive:!0}),await fs183.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6492
- `,{encoding:"utf-8",flag:"wx"}),await fs183.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs183.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,relativePath2.split(path304.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path304.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2},null,2)}var write_pr_review_trigger_eval=createSwarmTool({description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,approve_plan_critic:()=>approve_plan_critic,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,plan_conflict_check:()=>plan_conflict_check,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,consensus_mine:()=>consensus_mine,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,pr_workflow_status:()=>pr_workflow_status,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}return tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames),tools}init_utils();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
6491
+ `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path303.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path303.sep).join("/"),finding_count:actionableIds.length},null,2)}var write_pr_review_artifact=createSwarmTool({description:"Persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run.",args:{kind:exports_external.enum(["findings","handoff"]),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]).optional(),records:exports_external.array(FindingSchema4).min(1).max(1000).optional(),handoff:HandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID27}from"node:crypto";import fs183 from"node:fs";import path304 from"node:path";var _internals217={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals217.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals217.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals217.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i).optional(),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional(),rows:exports_external.array(PrReviewWriterInputRowSchema).min(1)}).strict();function failure4(message){return JSON.stringify({success:!1,message},null,2)}async function executeWritePrReviewTriggerEval(args2,directory,context={}){let writerLedger;try{writerLedger=validatePrReviewWriterInputLedger(typeof args2==="object"&&args2!==null?args2.rows:void 0)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let parsed=WritePrReviewTriggerEvalArgsSchema.safeParse(args2);if(!parsed.success)return failure4(`Invalid trigger evaluation: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");let gateState;try{gateState=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(gateState?.mode!=="PR_REVIEW"||!gateState.prHeadSha)return failure4("PR_REVIEW trigger evaluation requires the current session to have an active, bound PR_REVIEW gate");if(gateState.prHeadSha!==parsed.data.pr_head_sha)return failure4(`PR_REVIEW trigger evaluation head mismatch: expected ${gateState.prHeadSha}, received ${parsed.data.pr_head_sha}`);if(gateState.prReviewArtifactRunId&&gateState.prReviewArtifactRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation run_id must match the findings artifact run "${gateState.prReviewArtifactRunId}"`);if(gateState.prReviewTriggerEvalRunId&&gateState.prReviewTriggerEvalRunId!==parsed.data.run_id)return failure4(`PR_REVIEW trigger evaluation is already bound to run "${gateState.prReviewTriggerEvalRunId}"`);try{await assertPrReviewBaseCoverageSettled(directory,sessionID)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(!gateState.prReviewTriggerLedger)return failure4("PR_REVIEW trigger evaluation requires the canonical ledger frozen by the first micro dispatch");let frozenLedger;try{frozenLedger=validatePrReviewInlineTriggerLedger(gateState.prReviewTriggerLedger)}catch(error93){return failure4(`Persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}let classificationDrift=frozenLedger.rows.filter((row,index)=>writerLedger.rows[index]?.result!==row.result).map((row)=>row.trigger_id);if(classificationDrift.length>0)return failure4(`PR_REVIEW trigger classification drift from the canonical ledger frozen across micro dispatches: ${classificationDrift.join(", ")}`);let triggerLedger;try{triggerLedger=validatePrReviewPersistedInputLedger(frozenLedger.rows.map((frozenRow,index)=>{let writerRow=writerLedger.rows[index];if(frozenRow.result==="NOT_TRIGGERED")return frozenRow;if(!writerRow||writerRow.result!=="MATCHED")throw Error(`missing MATCHED provenance for ${frozenRow.trigger_id}`);return{...frozenRow,source_batch_id:writerRow.source_batch_id,source_lane_id:writerRow.source_lane_id}}))}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let validatedRows=triggerLedger.rows,currentRevisionDigest=await resolveCurrentRevisionDigest(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4("Active PR_REVIEW trigger evaluation could not bind the current exact revision digest");let citedLaneOwnership=new Map;for(let row of validatedRows){if(row.result!=="MATCHED")continue;let record3=findByBatchId(directory,row.source_batch_id,{parentSessionId:sessionID}).find((candidate2)=>candidate2.laneId===row.source_lane_id),recordOwnedLanes=record3?.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3?.workflowLane?[record3.workflowLane]:[];citedLaneOwnership.set(`${row.source_batch_id}\x00${row.source_lane_id}`,recordOwnedLanes);let outputRef=record3?.result?.outputRef?.trim(),outputArtifact=outputRef?readLaneOutput(directory,outputRef):null;if(!record3||record3.mode!=="swarm-pr-review:micro"||!recordOwnedLanes.includes(row.trigger_id)||record3.status!=="completed"||record3.result?.outputDegraded===!0||record3.result?.transcriptIncomplete===!0||record3.result?.truncated===!0||(record3.result?.chars??0)<=0||!record3.result?.digest?.trim()||!record3.result?.outputRef?.trim()||!outputArtifact||outputArtifact.artifact.batchId!==row.source_batch_id||outputArtifact.artifact.laneId!==row.source_lane_id||outputArtifact.artifact.mode!=="swarm-pr-review:micro"||outputArtifact.artifact.sessionId!==record3.subagentSessionId||outputArtifact.artifact.parentSessionId!==record3.parentSessionId||outputArtifact.artifact.agent!==record3.swarmPrefixedAgent||outputArtifact.artifact.role!==record3.normalizedAgent||outputArtifact.artifact.source!=="collect_lane_results"||outputArtifact.artifact.workflowLane!==record3.workflowLane||outputArtifact.artifact.prHeadSha!==record3.workspace?.prHeadSha||outputArtifact.artifact.gitHead!==record3.workspace?.gitHead||outputArtifact.artifact.revisionDigest!==currentRevisionDigest||outputArtifact.artifact.digest!==record3.result?.digest||outputArtifact.artifact.chars!==record3.result?.chars||!recordOwnedLanes.every((ownedFamily)=>prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,ownedFamily,recordOwnedLanes,record3.mode))||record3.workspace?.prHeadSha!==parsed.data.pr_head_sha||record3.workspace?.gitHead!==parsed.data.pr_head_sha)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a completed non-degraded micro-lane artifact`)}let citedLaneEntries=[...citedLaneOwnership.entries()];for(let i=0;i<citedLaneEntries.length;i++)for(let j=i+1;j<citedLaneEntries.length;j++){let[keyA,ownedA]=citedLaneEntries[i],[keyB,ownedB]=citedLaneEntries[j],overlap2=ownedA.filter((family)=>ownedB.includes(family));if(overlap2.length>0)return failure4(`PR_REVIEW trigger evaluation cites two lanes with overlapping ownership: "${keyA}" and "${keyB}" both declare ${overlap2.join(", ")}`)}let matchedFamilySet=new Set(triggerLedger.matchedIds),citedOwnershipSet=new Set(citedLaneEntries.flatMap(([,owned])=>owned)),ownershipOutsideMatchedLedger=[...citedOwnershipSet].filter((family)=>!matchedFamilySet.has(family)),matchedWithoutOwnedLane=[...matchedFamilySet].filter((family)=>!citedOwnershipSet.has(family));if(ownershipOutsideMatchedLedger.length>0||matchedWithoutOwnedLane.length>0)return failure4(`PR_REVIEW cited lane ownership must equal the MATCHED trigger set; owned but NOT_TRIGGERED/unlisted: ${ownershipOutsideMatchedLedger.join(", ")||"(none)"}; MATCHED without cited ownership: ${matchedWithoutOwnedLane.join(", ")||"(none)"}`);if(!parsed.data.base_sha)return failure4("Active PR_REVIEW trigger evaluation requires the exact merge-base base_sha");if(!parsed.data.base_ref)return failure4("Active PR_REVIEW trigger evaluation requires the exact live base_ref used to verify base_sha");let resolvedMergeBase=_internals217.resolveMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedMergeBase)return failure4("Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref and pr_head_sha");if(resolvedMergeBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW merge-base mismatch: expected ${resolvedMergeBase}, received ${parsed.data.base_sha}`);if(gateState.prReviewBaseRef!==parsed.data.base_ref||gateState.prReviewBaseSha!==parsed.data.base_sha.toLowerCase())return failure4(`PR_REVIEW trigger evaluation scope mismatch: workflow is bound to ${gateState.prReviewBaseRef??"(unbound)"} at ${gateState.prReviewBaseSha??"(unbound)"}, received ${parsed.data.base_ref} at ${parsed.data.base_sha}`);let matchedCount=validatedRows.filter((row)=>row.result==="MATCHED").length,dispatchedMicroLaneCount2=new Set(validatedRows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size,microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[gateState.prReviewDepthTier??"L"],matchedCount);if(dispatchedMicroLaneCount2<microFloor)return failure4(`PR_REVIEW micro lane floor unmet: depth tier ${gateState.prReviewDepthTier??"L"} requires at least ${microFloor} dispatched micro lane(s) across the attestation; the ledger attributes ${matchedCount} matched families to only ${dispatchedMicroLaneCount2}`);let artifact=buildPrReviewTriggerReceiptV2({run_id:parsed.data.run_id,pr_head_sha:parsed.data.pr_head_sha,base_ref:parsed.data.base_ref,base_sha:parsed.data.base_sha,evaluated_at:new Date().toISOString(),dispatched_micro_lane_count:dispatchedMicroLaneCount2,rows:validatedRows}),relativePath2=path304.join("pr-review",parsed.data.run_id,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}if(fs183.existsSync(destination))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${parsed.data.run_id}" and cannot be overwritten; abort the workflow with abort_pr_workflow to restart`);let parent=path304.dirname(destination),tempPath=path304.join(parent,`.trigger-eval.${randomUUID27()}.tmp`);try{await fs183.promises.mkdir(parent,{recursive:!0}),await fs183.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6492
+ `,{encoding:"utf-8",flag:"wx"}),await fs183.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs183.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,parsed.data.run_id,relativePath2.split(path304.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path304.sep).join("/"),trigger_count:artifact.trigger_count,matched_count:artifact.matched_count,not_triggered_count:artifact.not_triggered_count,no_match_count:artifact.no_match_count,dispatched_micro_lane_count:dispatchedMicroLaneCount2},null,2)}var write_pr_review_trigger_eval=createSwarmTool({description:"Persist the complete, exact-set PR-review trigger receipt after every MATCHED family has completed. Supply classifications and MATCHED provenance; evidence is optional and non-authoritative because the receipt reuses evidence frozen by the first micro dispatch. NOT_TRIGGERED families remain provenance-free.",args:{run_id:WritePrReviewTriggerEvalArgsSchema.shape.run_id,pr_head_sha:WritePrReviewTriggerEvalArgsSchema.shape.pr_head_sha,base_sha:WritePrReviewTriggerEvalArgsSchema.shape.base_sha,base_ref:WritePrReviewTriggerEvalArgsSchema.shape.base_ref,rows:WritePrReviewTriggerEvalArgsSchema.shape.rows},execute:executeWritePrReviewTriggerEval});init_write_retro();function defineHandlers(handlers){return handlers}var TOOL_MANIFEST=defineHandlers({diff:()=>diff,diff_summary:()=>diff_summary,syntax_check:()=>syntax_check,placeholder_scan:()=>placeholder_scan,imports:()=>imports,lint:()=>lint,secretscan:()=>secretscan,sast_scan:()=>sast_scan,build_check:()=>build_check,pre_check_batch:()=>pre_check_batch,quality_budget:()=>quality_budget,symbols:()=>symbols,complexity_hotspots:()=>complexity_hotspots,schema_drift:()=>schema_drift,todo_extract:()=>todo_extract,evidence_check:()=>evidence_check,check_gate_status:()=>check_gate_status,completion_verify:()=>completion_verify,complete_pr_workflow:()=>complete_pr_workflow,abort_pr_workflow:()=>abort_pr_workflow,approve_plan_critic:()=>approve_plan_critic,prepare_pr_workflow_checkout:()=>prepare_pr_workflow_checkout,run_pr_feedback_stage_a:()=>run_pr_feedback_stage_a,submit_council_verdicts:()=>submit_council_verdicts,submit_phase_council_verdicts:()=>submit_phase_council_verdicts,declare_council_criteria:()=>declare_council_criteria,sbom_generate:()=>sbom_generate,checkpoint:()=>checkpoint,pkg_audit:()=>pkg_audit,parse_lane_candidates:()=>parse_lane_candidates,plan_conflict_check:()=>plan_conflict_check,prepare_pr_feedback_scope:()=>prepare_pr_feedback_scope,write_pr_review_artifact:()=>write_pr_review_artifact,write_pr_review_trigger_eval:()=>write_pr_review_trigger_eval,test_runner:()=>test_runner,test_impact:()=>test_impact,mutation_test:()=>mutation_test,generate_mutants:()=>generate_mutants,detect_domains:()=>detect_domains,git_blame:()=>git_blame,gitingest:()=>gitingest,retrieve_summary:()=>retrieve_summary,retrieve_lane_output:()=>retrieve_lane_output,extract_code_blocks:()=>extract_code_blocks,phase_complete:()=>phase_complete,save_plan:()=>save_plan,update_task_status:()=>update_task_status,lint_spec:()=>lint_spec,write_retro:()=>write_retro,write_drift_evidence:()=>write_drift_evidence,write_hallucination_evidence:()=>write_hallucination_evidence,write_mutation_evidence:()=>write_mutation_evidence,declare_scope:()=>declare_scope,knowledge_query:()=>knowledge_query,doc_scan:()=>doc_scan,doc_extract:()=>doc_extract,curator_analyze:()=>curator_analyze,consensus_mine:()=>consensus_mine,knowledge_add:()=>knowledge_add,knowledge_recall:()=>knowledge_recall,knowledge_remove:()=>knowledge_remove,co_change_analyzer:()=>co_change_analyzer,context_status:()=>context_status,search:()=>search,ast_grep:()=>ast_grep,actionlint_scan:()=>actionlint_scan,osv_scan:()=>osv_scan,gh_evidence:()=>gh_evidence,pr_workflow_status:()=>pr_workflow_status,batch_symbols:()=>batch_symbols,suggest_patch:()=>suggestPatch,req_coverage:()=>req_coverage,get_approved_plan:()=>get_approved_plan,repo_map:()=>repo_map,get_qa_gate_profile:()=>get_qa_gate_profile,set_qa_gates:()=>set_qa_gates,web_search:()=>web_search,web_fetch:()=>web_fetch,convene_general_council:()=>convene_general_council,write_final_council_evidence:()=>write_final_council_evidence,skill_generate:()=>skill_generate,skill_list:()=>skill_list,skill_apply:()=>skill_apply,skill_inspect:()=>skill_inspect,run_stale_reconciliation:()=>run_stale_reconciliation,skill_regenerate:()=>skill_regenerate,skill_retire:()=>skill_retire,skill_improve:()=>skill_improve,spec_write:()=>spec_write,knowledge_receipt:()=>knowledge_receipt,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_command:()=>swarm_command,dispatch_lanes:()=>dispatch_lanes,dispatch_lanes_async:()=>dispatch_lanes_async,collect_lane_results:()=>collect_lane_results,summarize_work:()=>summarize_work,write_architecture_supervisor_evidence:()=>write_architecture_supervisor_evidence,lean_turbo_plan_lanes:()=>lean_turbo_plan_lanes,lean_turbo_acquire_locks:()=>lean_turbo_acquire_locks,lean_turbo_runner_status:()=>lean_turbo_runner_status,lean_turbo_review:()=>lean_turbo_review,lean_turbo_run_phase:()=>lean_turbo_run_phase,lean_turbo_status:()=>lean_turbo_status,swarm_apply_patch:()=>swarmApplyPatch2,external_skill_discover:()=>external_skill_discover,external_skill_list:()=>external_skill_list,external_skill_inspect:()=>external_skill_inspect,external_skill_promote:()=>external_skill_promote,external_skill_reject:()=>external_skill_reject,external_skill_delete:()=>external_skill_delete,external_skill_revoke:()=>external_skill_revoke,epic_decide_phase:()=>epic_decide_phase,epic_plan_waves:()=>epic_plan_waves,epic_record_divergence:()=>epic_record_divergence});function buildPluginToolObject(agents,config3,evaluationModelDispatcher,reviewModelDispatcher,generatedAgentNames=Object.keys(agents),reviewAgentModelRegistry,getActiveAgentName){let tools={},reviewAgentNames=Object.freeze([...generatedAgentNames]),knowledgeEnabled=config3?.knowledge?.enabled!==!1,knowledgeTools=new Set(["knowledge_add","knowledge_recall","knowledge_remove","knowledge_query","knowledge_receipt","knowledge_archive"]);for(let[name,handler]of Object.entries(TOOL_MANIFEST)){if(!knowledgeEnabled&&knowledgeTools.has(name))continue;tools[name]=handler()}return tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames),tools}init_utils();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
6493
6493
  `);if(lines.length<=maxLines)return output;let omittedCount=lines.length-maxLines,headLines=lines.slice(0,maxLines-tailLines),tailContent=lines.slice(-tailLines),footerLines=[];if(footerLines.push(""),footerLines.push(`[... ${omittedCount} line${omittedCount===1?"":"s"} omitted ...]`),toolName)footerLines.push(`Tool: ${toolName}`);return footerLines.push("Use /swarm retrieve <id> to get the full content"),`${headLines.join(`
6494
6494
  `)}
6495
6495
  ${tailContent.join(`