opencode-swarm 7.140.5 → 7.140.6

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 (45) hide show
  1. package/.opencode/skills/swarm-pr-review/SKILL.md +2 -4
  2. package/.opencode/skills/swarm-pr-review/references/lane-output-recoverability.md +54 -0
  3. package/dist/background/candidate-contract.d.ts +1 -1
  4. package/dist/background/pr-review-trigger-contract.d.ts +36 -0
  5. package/dist/cli/{config-doctor-5vzpq4qa.js → config-doctor-y5qeh18c.js} +2 -2
  6. package/dist/cli/{core-xjzdc56e.js → core-pwd9604e.js} +1 -1
  7. package/dist/cli/{curator-llm-factory-rds75zhj.js → curator-llm-factory-96pnc23w.js} +16 -16
  8. package/dist/cli/{curator-5nytvg7p.js → curator-q1nchgpg.js} +16 -16
  9. package/dist/cli/{evidence-summary-service-zq4gyx6g.js → evidence-summary-service-18142mr3.js} +4 -4
  10. package/dist/cli/{guardrail-explain-an7jvam1.js → guardrail-explain-kyd89z8z.js} +17 -17
  11. package/dist/cli/{guardrail-log-0hnd2k9v.js → guardrail-log-cahp1ews.js} +3 -3
  12. package/dist/cli/{hive-promoter-qe8pqg79.js → hive-promoter-vcbcvcsh.js} +16 -16
  13. package/dist/cli/{index-ptn13xjn.js → index-1p72dtym.js} +1 -1
  14. package/dist/cli/{index-ex7r16gc.js → index-2778hhh7.js} +2 -2
  15. package/dist/cli/{index-0rx9t9w8.js → index-4s7xgzbm.js} +1 -1
  16. package/dist/cli/{index-wrb0gykj.js → index-4zxrkk1h.js} +1 -1
  17. package/dist/cli/{index-2bg901qt.js → index-56rqw2hs.js} +2 -2
  18. package/dist/cli/{index-mm2egvdt.js → index-5qd5vt2d.js} +18 -18
  19. package/dist/cli/{index-affh1gtg.js → index-92n3d5ky.js} +3 -3
  20. package/dist/cli/{index-wkt9fj06.js → index-bjqpdr83.js} +2 -2
  21. package/dist/cli/{index-8rp1y4ab.js → index-dtqjxfw9.js} +1 -1
  22. package/dist/cli/{index-0r2m0vbq.js → index-e58e3v0v.js} +3 -3
  23. package/dist/cli/{index-01ggt2mj.js → index-fejfzy2j.js} +4 -4
  24. package/dist/cli/{index-ztgn70jz.js → index-h01wb18g.js} +1 -1
  25. package/dist/cli/{index-z90nvqj3.js → index-nakkgkkt.js} +151 -63
  26. package/dist/cli/{index-nyjtzmsj.js → index-p04qrwck.js} +2 -2
  27. package/dist/cli/{index-z7h37d63.js → index-p2ty3eee.js} +1 -1
  28. package/dist/cli/{index-jm4cpp4n.js → index-thp186x0.js} +1 -1
  29. package/dist/cli/{index-386ts4tm.js → index-y9q9f6ms.js} +1 -1
  30. package/dist/cli/{index-e0mpz2j3.js → index-z0z9pe7b.js} +5 -5
  31. package/dist/cli/{index-kb5q9v34.js → index-z3s0a44b.js} +3 -3
  32. package/dist/cli/{index-nwrwy8eb.js → index-zd4qhnr7.js} +1 -1
  33. package/dist/cli/index.js +16 -16
  34. package/dist/cli/{knowledge-escalator-4pfrc902.js → knowledge-escalator-gj58za4g.js} +6 -6
  35. package/dist/cli/{knowledge-events-3zkfnksk.js → knowledge-events-3m5jnnv6.js} +4 -4
  36. package/dist/cli/{knowledge-store-dpqgvvjt.js → knowledge-store-0vy8wbzd.js} +1 -1
  37. package/dist/cli/{knowledge-validator-2c7w87dk.js → knowledge-validator-mvcs8wf6.js} +2 -2
  38. package/dist/cli/{scan-cursor-1z60gwrw.js → scan-cursor-wznc7p7p.js} +2 -2
  39. package/dist/cli/{schema-vpnkwvez.js → schema-k596bhds.js} +1 -1
  40. package/dist/cli/{scope-persistence-p9dmprry.js → scope-persistence-0ny5fn07.js} +4 -4
  41. package/dist/cli/{skill-generator-yx7ka1cj.js → skill-generator-vrks0jjj.js} +7 -7
  42. package/dist/cli/{worktree-isolation-bwc6ra8e.js → worktree-isolation-zgk7314k.js} +16 -16
  43. package/dist/hooks/pr-workflow-gate.d.ts +20 -0
  44. package/dist/index.js +12 -10
  45. 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.140.5",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.140.6",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","check:events":"bun run scripts/check-event-contract.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"^4.1.8"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"mark a phase as complete and track dispatched agents",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, model-limit, usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary. Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). Non-blocking polls include pending lane identities by default and process settled lanes incrementally while continuing independent work; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function deepMergeInternal(base,override,depth){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return deepMergeInternal(base,override,0)}var MAX_MERGE_DEPTH=10;function freezeSet(items){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},deleteProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},defineProperty(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")},setPrototypeOf(){throw TypeError("CLAUDE_CODE_NATIVE_COMMANDS is readonly")}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -163,17 +163,19 @@ STRICT ceremony: require an effective spec, run the complete clarification funne
163
163
  ${append}`;return base}import{randomUUID}from"node:crypto";import*as fsp from"node:fs/promises";import*as path3 from"node:path";function bundledProjectSkillFileReference(slug){return`file:${BUNDLED_PROJECT_SKILL_ROOT}/${slug}/SKILL.md`}function describeBundledSkillSyncFailure(err){return`[opencode-swarm] Could not install bundled project skills; continuing without sync: ${err instanceof Error?err.message:String(err)}`}async function isSymbolicLinkAsync(p){try{return(await fsp.lstat(p)).isSymbolicLink()}catch{return!1}}async function ensureNotSymlinkedDirectoryAsync(p){try{let stat4=await fsp.lstat(p);return stat4.isDirectory()&&!stat4.isSymbolicLink()}catch(err){return err.code==="ENOENT"}}async function pathExistsAsync(p){try{return await fsp.access(p),!0}catch{return!1}}async function collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeDir=""){let currentSource=path3.join(sourceDir,relativeDir),entries=await fsp.readdir(currentSource,{withFileTypes:!0});entries.sort((a,b)=>a.name.localeCompare(b.name));let files=[];for(let entry of entries){let relativeEntry=path3.join(relativeDir,entry.name),sourcePath=path3.join(sourceDir,relativeEntry);if(entry.isSymbolicLink()||await isSymbolicLinkAsync(sourcePath))throw Error("refusing to copy symlinked bundled skill entry");if(entry.isDirectory()){files.push(...await collectBundledSkillFilesBoundedAsync(sourceDir,state,relativeEntry));continue}if(!entry.isFile())continue;let stat4=await fsp.stat(sourcePath),nextFiles=state.files+1,nextBytes=state.bytes+stat4.size;if(nextFiles>MAX_SKILL_FILES||nextBytes>MAX_SKILL_BYTES)throw Error("bundled skill package exceeds copy bounds");state.files=nextFiles,state.bytes=nextBytes,files.push({relativePath:relativeEntry})}return files}async function ensureContainedDirectoryAsync(rootDir,directory){let safeRoot=path3.resolve(rootDir),safeDirectory=path3.resolve(directory),relative2=path3.relative(safeRoot,safeDirectory);if(relative2.startsWith("..")||path3.isAbsolute(relative2))throw Error("bundled skill destination escaped its private root");try{let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;await fsp.mkdir(safeRoot,{recursive:!0});let rootStat=await fsp.lstat(safeRoot);if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}let current=safeRoot;for(let segment of relative2.split(path3.sep).filter(Boolean)){current=path3.join(current,segment);try{let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}catch(err){if(err.code!=="ENOENT")throw err;try{await fsp.mkdir(current)}catch(mkdirErr){if(mkdirErr.code!=="EEXIST")throw mkdirErr}let stat4=await fsp.lstat(current);if(stat4.isSymbolicLink()||!stat4.isDirectory())throw Error("refusing to traverse unsafe bundled skill directory")}}}async function rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles=[]){let safeDestDir=path3.resolve(destDir),dirs=new Set;for(let copiedFile of copiedFiles){let resolvedFile=path3.resolve(copiedFile),relative2=path3.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path3.isAbsolute(relative2))continue;try{await fsp.rm(resolvedFile,{force:!0})}catch{}dirs.add(path3.dirname(resolvedFile))}for(let overwritten of overwrittenFiles.reverse()){let resolvedFile=path3.resolve(overwritten.path),relative2=path3.relative(safeDestDir,resolvedFile);if(relative2.startsWith("..")||path3.isAbsolute(relative2))continue;try{await fsp.writeFile(resolvedFile,overwritten.contents)}catch{}}for(let dir of[...dirs].sort((a,b)=>b.length-a.length)){let relative2=path3.relative(safeDestDir,path3.resolve(dir));if(relative2.startsWith("..")||path3.isAbsolute(relative2))continue;try{await fsp.rmdir(dir)}catch{}}}async function copyFileAtomicAsync(sourcePath,destPath){let tempPath=path3.join(path3.dirname(destPath),`.${path3.basename(destPath)}.tmp.${randomUUID()}`);try{await fsp.copyFile(sourcePath,tempPath),await fsp.rename(tempPath,destPath)}catch(err){try{await fsp.rm(tempPath,{force:!0})}catch{}throw err}}async function copyBundledDirectoryBoundedAsync(sourceDir,destDir){let files=await collectBundledSkillFilesBoundedAsync(sourceDir,{files:0,bytes:0}),copiedFiles=[],overwrittenFiles=[];try{for(let file2 of files){let sourcePath=path3.join(sourceDir,file2.relativePath),destPath=path3.join(destDir,file2.relativePath);if(await ensureContainedDirectoryAsync(destDir,path3.dirname(destPath)),await pathExistsAsync(destPath)){if(await isSymbolicLinkAsync(destPath))throw Error("refusing to overwrite symlinked bundled skill file");let[sourceContents,destContents]=await Promise.all([fsp.readFile(sourcePath),fsp.readFile(destPath)]);if(sourceContents.equals(destContents))continue;overwrittenFiles.push({path:destPath,contents:destContents}),await copyFileAtomicAsync(sourcePath,destPath)}else await copyFileAtomicAsync(sourcePath,destPath),copiedFiles.push(destPath)}}catch(err){throw await rollbackCopiedFilesAsync(copiedFiles,destDir,overwrittenFiles),err}}async function performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet){try{let sourceRoot=path3.join(packageRoot,".opencode","skills"),swarmDir=path3.join(projectDirectory,".swarm"),skillsDir=path3.join(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT);if(!await ensureNotSymlinkedDirectoryAsync(sourceRoot))throw Error("refusing to copy symlinked bundled skill source root");if(!await ensureNotSymlinkedDirectoryAsync(swarmDir))return;if(!await ensureNotSymlinkedDirectoryAsync(skillsDir))return;for(let slug of BUNDLED_PROJECT_SKILLS){let sourceDir=path3.join(sourceRoot,slug),sourceSkill=path3.join(sourceDir,"SKILL.md"),destDir=path3.join(skillsDir,slug);if(!await pathExistsAsync(sourceSkill))continue;if(!await ensureNotSymlinkedDirectoryAsync(sourceDir))throw Error("refusing to copy symlinked bundled skill directory");if(!await ensureNotSymlinkedDirectoryAsync(destDir))continue;await copyBundledDirectoryBoundedAsync(sourceDir,destDir),log("synchronized bundled skill",{slug:bundledProjectSkillFileReference(slug)})}}catch(err){let failureMsg=describeBundledSkillSyncFailure(err);if(quiet)advisoryWarn(failureMsg);else console.warn(failureMsg)}}async function syncBundledProjectSkillsIfMissingAsync(projectDirectory,packageRoot,quiet=!1){let syncKey=path3.resolve(projectDirectory,BUNDLED_PROJECT_SKILL_ROOT),existing=inFlightSyncs.get(syncKey);if(existing)return existing;if(inFlightSyncs.size>=MAX_IN_FLIGHT_SYNCS){log("skipping bundled skill sync because the in-flight limit was reached",{limit:MAX_IN_FLIGHT_SYNCS});return}let syncPromise=performBundledProjectSkillSyncAsync(projectDirectory,packageRoot,quiet).finally(()=>{if(inFlightSyncs.get(syncKey)===syncPromise)inFlightSyncs.delete(syncKey)});return inFlightSyncs.set(syncKey,syncPromise),syncPromise}var BUNDLED_PROJECT_SKILLS,BUNDLED_PROJECT_SKILL_ROOT=".swarm/bundled-skills",MAX_SKILL_FILES=64,MAX_SKILL_BYTES=512000,MAX_IN_FLIGHT_SYNCS=64,inFlightSyncs;var init_bundled_skills=__esm(()=>{init_warning_buffer();init_logger();BUNDLED_PROJECT_SKILLS=["brainstorm","specify","clarify-spec","resume","clarify","discover","consult","pre-phase-briefing","council","deep-dive","deep-research","codebase-review-swarm","swarm-implement","design-docs","swarm-pr-review","swarm","swarm-pr-feedback","swarm-pr-subscribe","swarm-ci-monitor","issue-ingest","plan","critic-gate","execute","phase-wrap","loop","writing-tests","running-tests","engineering-conventions","commit-pr","ci-failure-batching","gate-attribution","merge-queue-readiness","skill-edit-validation","worktree-retry-cleanup","test-file-split","fork-pr-operations","parallel-work-check","ci-fix-monitor","issue-tracer","orchestrating-subagents","durable-session-state"];inFlightSyncs=new Map});function formatCandidateHeader(family){return["[CANDIDATE]",...CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name)].join(" | ")}function formatCleanTemplate(family){return["[CLEAN]",family==="base_explorer"?"lane":"micro_lane","coverage_scope","evidence"].join(" | ")}function candidateHeaderFamily(fields){if(fields[0]?.trim()!=="[CANDIDATE]")return null;let normalized=fields.slice(1).map((field)=>field.trim());for(let family of["base_explorer","micro_lane"]){let canonicalHeaderFields=CANDIDATE_FIELDS[family].map((name)=>name==="file_line"?"file:line":name);if(normalized.length===canonicalHeaderFields.length&&canonicalHeaderFields.every((name,index)=>normalized[index]===name))return family}return null}function selectCandidateHeader(lines){let markerlessFallback=null;for(let[lineIndex,line]of lines.entries()){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());if(fields.length<2||!fields.some(Boolean))continue;let markerBearing=fields[0]==="[CANDIDATE]",selection={lineIndex,fields,family:candidateHeaderFamily(fields),markerBearing};if(markerBearing)return selection;markerlessFallback??=selection}return markerlessFallback}function removeCandidateCodeFences(text){let lines=[],inFence=!1;for(let rawLine of text.split(`
164
164
  `)){if(rawLine.trimStart().startsWith("```")){inFence=!inFence;continue}if(!inFence)lines.push(rawLine)}return lines.join(`
165
165
  `)}function parseClosedMarkdownFences(text){let lines=text.split(/\r?\n/),blocks=[],fencedLineIndexes=new Set,openingLine=-1,openingWidth=0;for(let index=0;index<lines.length;index+=1){let line=lines[index];if(openingLine<0){let opening=line.match(/^\s{0,3}(`{3,})([^`]*)$/);if(!opening)continue;openingLine=index,openingWidth=opening[1].length;continue}let closing=line.match(/^\s{0,3}(`{3,})\s*$/);if(!closing||closing[1].length<openingWidth)continue;let content=lines.slice(openingLine+1,index);blocks.push({openingLine,closingLine:index,content});for(let fenced=openingLine;fenced<=index;fenced+=1)fencedLineIndexes.add(fenced);openingLine=-1,openingWidth=0}if(openingLine>=0)return null;return{lines,blocks,unfencedLines:lines.filter((_,index)=>!fencedLineIndexes.has(index))}}function lineCarriesCandidateProtocol(line){let fields=splitPipeFields(line.trim()).map((field)=>field.trim());return fields[0]==="[CANDIDATE]"||fields[0]==="[CLEAN]"||candidateHeaderFamily(fields)!==null}function lastUnescapedPipeIndex(line){let last=-1;for(let index=0;index<line.length;index+=1){if(line[index]==="\\"&&line[index+1]==="|"){index+=1;continue}if(line[index]==="|")last=index}return last}function repairRedundantCleanConfidenceLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields.length!==5||fields[0]!=="[CLEAN]"||!isCandidateConfidence(fields[4])||!analyzeCleanFields(fields.slice(0,4),family).valid)return{line,repaired:!1};let delimiter=lastUnescapedPipeIndex(line);if(delimiter<0)return{line,repaired:!1};return{line:line.slice(0,delimiter).trimEnd(),repaired:!0}}function repairRedundantCleanConfidence(text,family){let repaired=!1;return{text:text.split(/\r?\n/).map((line)=>{let result=repairRedundantCleanConfidenceLine(line,family);return repaired||=result.repaired,result.line}).join(`
166
+ `),repaired}}function dropNonContractMarkerRows(text){let lines=text.split(/\r?\n/),kept=lines.filter((line)=>{if(!line.includes("|"))return!0;let firstField=splitPipeFields(line.trim())[0]?.trim()??"";return!NON_CONTRACT_MARKER_LINE.test(firstField)});return{text:kept.join(`
167
+ `),dropped:kept.length!==lines.length}}function repairCleanEvidencePipesLine(line){if(splitPipeFields(line)[0]?.trim()!=="[CLEAN]")return{line,repaired:!1};let separatorCount=0,out="";for(let index=0;index<line.length;index+=1){let char=line[index];if(char==="\\"&&line[index+1]==="|"){out+="\\|",index+=1;continue}if(char==="|"){separatorCount+=1,out+=separatorCount<=3?"|":"\\|";continue}out+=char}return separatorCount>3?{line:out,repaired:!0}:{line,repaired:!1}}function repairCleanEvidencePipes(text){let repaired=!1;return{text:text.split(/\r?\n/).map((line)=>{let result=repairCleanEvidencePipesLine(line);return repaired||=result.repaired,result.line}).join(`
166
168
  `),repaired}}function isStrictProtocolDataLine(line,family){let clean=repairRedundantCleanConfidenceLine(line,family).line,fields=splitPipeFields(clean).map((field)=>field.trim());if(fields[0]==="[CLEAN]")return analyzeCleanFields(fields,family).valid;if(fields[0]==="[CANDIDATE]")return analyzeCandidateFields(fields.slice(1),family).valid;return analyzeCandidateFields(fields,family).valid}function recoverTerminalProtocolFence(rawText,family){let parsed=parseClosedMarkdownFences(rawText);if(!parsed||parsed.blocks.length===0)return null;if(parsed.unfencedLines.some(lineCarriesCandidateProtocol))return null;let lastNonblankLine=parsed.lines.length-1;while(lastNonblankLine>=0&&parsed.lines[lastNonblankLine].trim().length===0)lastNonblankLine-=1;let terminal=parsed.blocks.at(-1);if(terminal.closingLine!==lastNonblankLine)return null;if(parsed.blocks.slice(0,-1).some((block)=>block.content.some(lineCarriesCandidateProtocol)))return null;let content=terminal.content.slice().map((line)=>line.trimEnd());while(content[0]?.trim()==="")content.shift();while(content.at(-1)?.trim()==="")content.pop();if(content[0]?.trim()!==CANDIDATE_HEADERS[family])return null;let rows=content.slice(1).filter((line)=>line.trim()!=="");if(rows.length===0||!rows.every((line)=>isStrictProtocolDataLine(line,family)))return null;let outside=parsed.unfencedLines.join(`
167
169
  `).trimEnd(),protocol=content.join(`
168
170
  `);return outside?`${outside}
169
- ${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],recoveredFence=recoverTerminalProtocolFence(rawText,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(rawText),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let text=cleanRepair.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(rawText).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CLEAN]")return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker==="[CANDIDATE]"||marker==="[CLEAN]"});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
170
- `),synthesizedHeader:!0,repairKinds}}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&&microBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&&microBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&&microBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=160)return normalized;return`${normalized.slice(0,160)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==9)issues.push({field:"row",message:`Expected exactly 9 candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null)issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==4)issues.push({field:"row",message:`Expected exactly 3 CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<12)issues.push({field:"coverage_scope",message:"coverage_scope must contain at least 12 characters"});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<20)issues.push({field:"evidence",message:"evidence must contain at least 20 characters"});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_FIELDS,CANDIDATE_HEADERS,CLEAN_TEMPLATES;var init_candidate_contract=__esm(()=>{CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence"]};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")}});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs3){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs3);if(!fs3.lutimes)patchLutimes(fs3);if(fs3.chown=chownFix(fs3.chown),fs3.fchown=chownFix(fs3.fchown),fs3.lchown=chownFix(fs3.lchown),fs3.chmod=chmodFix(fs3.chmod),fs3.fchmod=chmodFix(fs3.fchmod),fs3.lchmod=chmodFix(fs3.lchmod),fs3.chownSync=chownFixSync(fs3.chownSync),fs3.fchownSync=chownFixSync(fs3.fchownSync),fs3.lchownSync=chownFixSync(fs3.lchownSync),fs3.chmodSync=chmodFixSync(fs3.chmodSync),fs3.fchmodSync=chmodFixSync(fs3.fchmodSync),fs3.lchmodSync=chmodFixSync(fs3.lchmodSync),fs3.stat=statFix(fs3.stat),fs3.fstat=statFix(fs3.fstat),fs3.lstat=statFix(fs3.lstat),fs3.statSync=statFixSync(fs3.statSync),fs3.fstatSync=statFixSync(fs3.fstatSync),fs3.lstatSync=statFixSync(fs3.lstatSync),fs3.chmod&&!fs3.lchmod)fs3.lchmod=function(path4,mode,cb){if(cb)process.nextTick(cb)},fs3.lchmodSync=function(){};if(fs3.chown&&!fs3.lchown)fs3.lchown=function(path4,uid,gid,cb){if(cb)process.nextTick(cb)},fs3.lchownSync=function(){};if(platform==="win32")fs3.rename=typeof fs3.rename!=="function"?fs3.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs3.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs3.rename);fs3.read=typeof fs3.read!=="function"?fs3.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs3,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs3,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs3.read),fs3.readSync=typeof fs3.readSync!=="function"?fs3.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs3,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs3.readSync);function patchLchmod(fs4){fs4.lchmod=function(path4,mode,callback){fs4.open(path4,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs4.fchmod(fd,mode,function(err2){fs4.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs4.lchmodSync=function(path4,mode){var fd=fs4.openSync(path4,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs4.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs4.closeSync(fd)}catch(er){}else fs4.closeSync(fd)}return ret}}function patchLutimes(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&fs4.futimes)fs4.lutimes=function(path4,at,mt,cb){fs4.open(path4,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs4.futimes(fd,at,mt,function(er2){fs4.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs4.lutimesSync=function(path4,at,mt){var fd=fs4.openSync(path4,constants.O_SYMLINK),ret,threw=!0;try{ret=fs4.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs4.closeSync(fd)}catch(er){}else fs4.closeSync(fd)}return ret};else if(fs4.futimes)fs4.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs4.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs3,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs3,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs3,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs3,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs3,target,options,callback):orig.call(fs3,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs3,target,options):orig.call(fs3,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs3){return{ReadStream,WriteStream};function ReadStream(path4,options){if(!(this instanceof ReadStream))return new ReadStream(path4,options);Stream.call(this);var self=this;this.path=path4,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs3.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path4,options){if(!(this instanceof WriteStream))return new WriteStream(path4,options);Stream.call(this),this.path=path4,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs3.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs3=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
171
+ ${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],summaryDrop=dropNonContractMarkerRows(rawText);if(summaryDrop.dropped)repairKinds.push("summary-row-dropped");let recoveredFence=recoverTerminalProtocolFence(summaryDrop.text,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(summaryDrop.text),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let pipeRepair=repairCleanEvidencePipes(cleanRepair.text);if(pipeRepair.repaired)repairKinds.push("clean-evidence-pipe-tail-merge");let text=pipeRepair.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(summaryDrop.text).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CLEAN]")return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker==="[CANDIDATE]"||marker==="[CLEAN]"});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
172
+ `),synthesizedHeader:!0,repairKinds}}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&&microBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&&microBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&&microBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=160)return normalized;return`${normalized.slice(0,160)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==9)issues.push({field:"row",message:`Expected exactly 9 candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null)issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==4)issues.push({field:"row",message:`Expected exactly 3 CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<12)issues.push({field:"coverage_scope",message:"coverage_scope must contain at least 12 characters"});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<20)issues.push({field:"evidence",message:"evidence must contain at least 20 characters"});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_FIELDS,CANDIDATE_HEADERS,CLEAN_TEMPLATES,NON_CONTRACT_MARKER_LINE;var init_candidate_contract=__esm(()=>{CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence"]};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")};NON_CONTRACT_MARKER_LINE=/^\[(?!(?:CANDIDATE|CLEAN)\])[A-Z][A-Z0-9_-]*\]/});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs3){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs3);if(!fs3.lutimes)patchLutimes(fs3);if(fs3.chown=chownFix(fs3.chown),fs3.fchown=chownFix(fs3.fchown),fs3.lchown=chownFix(fs3.lchown),fs3.chmod=chmodFix(fs3.chmod),fs3.fchmod=chmodFix(fs3.fchmod),fs3.lchmod=chmodFix(fs3.lchmod),fs3.chownSync=chownFixSync(fs3.chownSync),fs3.fchownSync=chownFixSync(fs3.fchownSync),fs3.lchownSync=chownFixSync(fs3.lchownSync),fs3.chmodSync=chmodFixSync(fs3.chmodSync),fs3.fchmodSync=chmodFixSync(fs3.fchmodSync),fs3.lchmodSync=chmodFixSync(fs3.lchmodSync),fs3.stat=statFix(fs3.stat),fs3.fstat=statFix(fs3.fstat),fs3.lstat=statFix(fs3.lstat),fs3.statSync=statFixSync(fs3.statSync),fs3.fstatSync=statFixSync(fs3.fstatSync),fs3.lstatSync=statFixSync(fs3.lstatSync),fs3.chmod&&!fs3.lchmod)fs3.lchmod=function(path4,mode,cb){if(cb)process.nextTick(cb)},fs3.lchmodSync=function(){};if(fs3.chown&&!fs3.lchown)fs3.lchown=function(path4,uid,gid,cb){if(cb)process.nextTick(cb)},fs3.lchownSync=function(){};if(platform==="win32")fs3.rename=typeof fs3.rename!=="function"?fs3.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs3.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs3.rename);fs3.read=typeof fs3.read!=="function"?fs3.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs3,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs3,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs3.read),fs3.readSync=typeof fs3.readSync!=="function"?fs3.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs3,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs3.readSync);function patchLchmod(fs4){fs4.lchmod=function(path4,mode,callback){fs4.open(path4,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs4.fchmod(fd,mode,function(err2){fs4.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs4.lchmodSync=function(path4,mode){var fd=fs4.openSync(path4,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs4.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs4.closeSync(fd)}catch(er){}else fs4.closeSync(fd)}return ret}}function patchLutimes(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&fs4.futimes)fs4.lutimes=function(path4,at,mt,cb){fs4.open(path4,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs4.futimes(fd,at,mt,function(er2){fs4.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs4.lutimesSync=function(path4,at,mt){var fd=fs4.openSync(path4,constants.O_SYMLINK),ret,threw=!0;try{ret=fs4.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs4.closeSync(fd)}catch(er){}else fs4.closeSync(fd)}return ret};else if(fs4.futimes)fs4.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs4.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs3,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs3,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs3,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs3,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs3,target,options,callback):orig.call(fs3,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs3,target,options):orig.call(fs3,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs3){return{ReadStream,WriteStream};function ReadStream(path4,options){if(!(this instanceof ReadStream))return new ReadStream(path4,options);Stream.call(this);var self=this;this.path=path4,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs3.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path4,options){if(!(this instanceof WriteStream))return new WriteStream(path4,options);Stream.call(this),this.path=path4,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs3.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs3=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
171
173
  GFS4: `),console.error(m)};if(!fs3[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs3,queue),fs3.close=function(fs$close){function close(fd,cb){return fs$close.call(fs3,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs3.close),fs3.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs3,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs3.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs3[gracefulQueue]),__require("assert").equal(fs3[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs3[gracefulQueue]);module.exports=patch(clone2(fs3));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs3.__patched)module.exports=patch(fs3),fs3.__patched=!0;function patch(fs4){polyfills(fs4),fs4.gracefulify=patch,fs4.createReadStream=createReadStream,fs4.createWriteStream=createWriteStream;var fs$readFile=fs4.readFile;fs4.readFile=readFile3;function readFile3(path4,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path4,options,cb);function go$readFile(path5,options2,cb2,startTime){return fs$readFile(path5,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path5,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs4.writeFile;fs4.writeFile=writeFile2;function writeFile2(path4,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path4,data,options,cb);function go$writeFile(path5,data2,options2,cb2,startTime){return fs$writeFile(path5,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path5,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs4.appendFile;if(fs$appendFile)fs4.appendFile=appendFile;function appendFile(path4,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path4,data,options,cb);function go$appendFile(path5,data2,options2,cb2,startTime){return fs$appendFile(path5,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path5,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs4.copyFile;if(fs$copyFile)fs4.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs4.readdir;fs4.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path4,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path5,options2,cb2,startTime){return fs$readdir(path5,fs$readdirCallback(path5,options2,cb2,startTime))}:function(path5,options2,cb2,startTime){return fs$readdir(path5,options2,fs$readdirCallback(path5,options2,cb2,startTime))};return go$readdir(path4,options,cb);function fs$readdirCallback(path5,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path5,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs4);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs4.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs4.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs4,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs4,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs4,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs4,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path4,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path4,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path4,options){return new fs4.ReadStream(path4,options)}function createWriteStream(path4,options){return new fs4.WriteStream(path4,options)}var fs$open=fs4.open;fs4.open=open;function open(path4,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path4,flags,mode,cb);function go$open(path5,flags2,mode2,cb2,startTime){return fs$open(path5,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path5,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs4}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs3[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs3[gracefulQueue].length;++i)if(fs3[gracefulQueue][i].length>2)fs3[gracefulQueue][i][3]=now,fs3[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs3[gracefulQueue].length===0)return;var elem=fs3[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs3[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs3,callback){let cachedPrecision=fs3[cacheSymbol];if(cachedPrecision)return fs3.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs3.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs3.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs3,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path4=__require("path"),fs3=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path4.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs3,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs3,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs3,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs3=require_graceful_fs();function createSyncFs(fs4){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs4};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs4[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve3,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve3(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs3),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger()});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync2 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path4 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync2.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync2.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path4.dirname(filePath),tempName=`.${path4.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path4.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve3)=>setTimeout(resolve3,ms))}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals4.platform()==="win32"){let taskkill;try{if(taskkill=_internals4.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals4.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve3)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve3(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function streamFromNode(pipe2){let collected,readerClaimed=!1,collect=()=>{if(readerClaimed)return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return collected??=new Promise((resolve3)=>{if(!pipe2){resolve3(Buffer.alloc(0));return}let chunks=[];pipe2.on("data",(chunk)=>{chunks.push(typeof chunk==="string"?Buffer.from(chunk):chunk)}),pipe2.on("end",()=>resolve3(Buffer.concat(chunks))),pipe2.on("error",()=>resolve3(Buffer.concat(chunks)))}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller){controller.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller){pipe2.on("data",(chunk)=>{controller.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller.close()),pipe2.on("error",(err)=>controller.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})};return{async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(readerClaimed||collected)throw TypeError("Subprocess output is already consumed");return readerClaimed=!0,toWebReadable().getReader()}}}function mapStdio(v){return v??"pipe"}function streamFromBun(stream){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller){controller.close()}}).getReader()}};let candidate=stream,collect=async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[];for(;;){let{done,value}=await reader.read();if(done)break;if(value)chunks.push(value)}let total=chunks.reduce((acc,c)=>acc+c.byteLength,0),out=new Uint8Array(total),off=0;for(let c of chunks)out.set(c,off),off+=c.byteLength;return out},text=typeof candidate.text==="function"?()=>candidate.text():async()=>new TextDecoder().decode(await collect()),bytes=typeof candidate.bytes==="function"?()=>candidate.bytes():collect,getReader=typeof candidate.getReader==="function"?()=>candidate.getReader():()=>new ReadableStream({start(controller){controller.close()}}).getReader();return{text,bytes,getReader}}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function bunSpawn(cmd,options){let bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let proc2=bun.spawn(cmd,spawnOpts),killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2)});return{stdout:streamFromBun(proc2.stdout),stderr:streamFromBun(proc2.stderr),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]}),killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve3)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve3(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=error49,resolve3(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle)});return{stdout:streamFromNode(proc.stdout),stderr:streamFromNode(proc.stderr),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function bunSpawnSync(cmd,options){let bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts=mergedEnv2!==void 0?{...options,env:mergedEnv2}:options;return bun.spawnSync(cmd,spawnOpts)}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0}),stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,_internals4;var init_bun_compat=__esm(()=>{_internals4={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller}});import*as fs3 from"node:fs";import*as path5 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
172
174
  → ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals5.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path5.normalize(path5.resolve(directory,".swarm")),resolved=path5.normalize(path5.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path5.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path5.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs3.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs3.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs3.existsSync(existingPath)){let parent=path5.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs3.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path5.normalize(candidate),normalizedBase=path5.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path5.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path5.sep}`)}async function readSwarmFileAsync(directory,filename,cache){if(cache!==void 0){let key=`${directory}::${filename}`,cached2=cache.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename);return cache.set(key,promise2),promise2}let ENOENT_MAX_ATTEMPTS=5,ENOENT_RETRY_DELAY_MS=10,maxAttempts=6;for(let attempt=0;attempt<maxAttempts;attempt++)try{let resolvedPath=_internals5.validateSwarmPath(directory,filename);return await _internals5.readCachedTextFile(resolvedPath,async()=>{return await bunFile(resolvedPath).text()})}catch(err){let code=err?.code;if(code==="ENOENT"){if(attempt>=ENOENT_MAX_ATTEMPTS-1)return null;await new Promise((resolve4)=>setTimeout(resolve4,ENOENT_RETRY_DELAY_MS));continue}if(!(code==="EBUSY"||code==="EPERM"||code==="EACCES")||attempt===maxAttempts-1)return null;let retryDelayMs=10*2**attempt;await new Promise((resolve4)=>setTimeout(resolve4,retryDelayMs))}return null}function estimateTokens(text){if(!text)return 0;return Math.ceil(text.length*0.33)}var _internals5;var init_utils2=__esm(()=>{init_utils();init_bun_compat();init_swarm_artifact_cache();_internals5={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash}from"node:crypto";import{appendFileSync,mkdirSync}from"node:fs";import*as path6 from"node:path";function isBidiCodePoint(code){for(let i=0;i<BIDI_RANGES.length;i++){let[lo,hi]=BIDI_RANGES[i];if(code>=lo&&code<=hi)return!0}return!1}function sanitizeString(value){let result="";for(let i=0;i<value.length;i++){let code=value.codePointAt(i)??0;if(code>65535)result+=value[i],i++,result+=value[i];else if(code===0)result+="\\u0000";else if(code===27){if(i+1<value.length&&value[i+1]==="["){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=48&&next<=63)i++;else if(next>=32&&next<=47)i++;else if(next>=64&&next<=126){i++;break}else break}}else if(i+1<value.length&&value[i+1]==="]"){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next===7){i++;break}else if(next===27&&i+2<value.length&&value[i+2]==="\\"){i+=2;break}else i++}}else if(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=32&&next<=47){i++;while(i+1<value.length){let b=value.charCodeAt(i+1);if(b>=48&&b<=126){i++;break}else if(b>=32&&b<=47)i++;else break}}else if(next>=48&&next<=126)i++}}else if(isBidiCodePoint(code));else result+=value[i]}return result}function sanitizeRecord(record2){for(let key of Object.keys(record2)){let value=record2[key];if(typeof value==="string")record2[key]=sanitizeString(value);else if(value!==null&&typeof value==="object")if(Array.isArray(value))for(let i=0;i<value.length;i++){let element=value[i];if(typeof element==="string")value[i]=sanitizeString(element);else if(element!==null&&typeof element==="object")sanitizeRecord(element)}else sanitizeRecord(value)}return record2}function computeBatchDigest(batchId){return createHash(BATCH_DIGEST_ALGORITHM).update(batchId).digest("hex")}function sidecarRelativePath(batchDigest){return path6.join("lane-results",batchDigest,"candidates.jsonl")}function validateRecord(record2,schema,label){let result=schema.safeParse(record2);if(!result.success)throw Error(`Sidecar ${label} schema validation failed: ${result.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")}`)}function withLockfile(lockDir,write){let lockPath=path6.join(lockDir,".lock"),release=import_proper_lockfile.default.lockSync(lockPath,{realpath:!1});try{return write()}finally{release()}}function appendToSidecar(options,batchId,envelope,candidates,cleanAttestation){let batchDigest=options.batchDigest??computeBatchDigest(batchId),relPath=sidecarRelativePath(batchDigest),absPath=validateSwarmPath(options.projectRoot,relPath);validateRecord(envelope,SidecarEnvelopeSchema,"envelope");for(let i=0;i<candidates.length;i++)validateRecord(candidates[i],SidecarCandidateSchema,`candidate[${i}]`);if(cleanAttestation!==void 0)validateRecord(cleanAttestation,SidecarCleanAttestationSchema,"clean_attestation");mkdirSync(path6.dirname(absPath),{recursive:!0});let sanitizedEnvelope=sanitizeRecord(structuredClone(envelope)),sanitizedCandidates=candidates.map((c)=>sanitizeRecord(structuredClone(c))),sanitizedCleanAttestation=cleanAttestation===void 0?void 0:sanitizeRecord(structuredClone(cleanAttestation)),lines=[JSON.stringify(sanitizedEnvelope)];if(sanitizedCleanAttestation)lines.push(JSON.stringify(sanitizedCleanAttestation));for(let candidate of sanitizedCandidates)lines.push(JSON.stringify(candidate));let payload=`${lines.join(`
173
175
  `)}
174
176
  `,doWrite=()=>{appendFileSync(absPath,payload,"utf-8")};if(options.useLockfile)withLockfile(path6.dirname(absPath),doWrite);else doWrite()}var import_proper_lockfile,BATCH_DIGEST_ALGORITHM="sha256",SidecarEnvelopeSchema,SidecarCleanAttestationSchema,SidecarCandidateCommon,SidecarCandidateSchema,BIDI_RANGES;var init_candidate_sidecar_store=__esm(()=>{init_zod();init_utils2();init_candidate_contract();import_proper_lockfile=__toESM(require_proper_lockfile(),1),SidecarEnvelopeSchema=exports_external.object({record_type:exports_external.literal("invocation"),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),produced_at:exports_external.string().min(1),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),format_families_detected:exports_external.array(exports_external.string()),candidate_count:exports_external.number().int().nonnegative(),parse_errors:exports_external.number().int().nonnegative(),malformed_rows:exports_external.number().int().nonnegative(),clean_attestation_count:exports_external.number().int().nonnegative().optional()}).strict(),SidecarCleanAttestationSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("base_explorer"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict(),exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("micro_lane"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),micro_lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict()]),SidecarCandidateCommon={record_type:exports_external.literal("candidate"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),extracted_from_partial_source:exports_external.boolean(),candidate_id:exports_external.string().min(1),severity:exports_external.enum(CANDIDATE_SEVERITIES),category:exports_external.string().min(1),file_line:exports_external.string().min(1),claim:exports_external.string().min(1),evidence_summary:exports_external.string().min(1),confidence:exports_external.enum(CANDIDATE_CONFIDENCES)},SidecarCandidateSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("base_explorer"),lane:exports_external.string().min(1),micro_lane:exports_external.null(),impact_context:exports_external.string().min(1),invariant_violated:exports_external.null()}).strict(),exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("micro_lane"),lane:exports_external.null(),micro_lane:exports_external.string().min(1),impact_context:exports_external.null(),invariant_violated:exports_external.string().min(1)}).strict()]),BIDI_RANGES=[[8234,8238],[8294,8297]]});function detectRowFormatFamily(rowFields){let trimmed=rowFields.map((f)=>f.trim()),hasImpactContext=trimmed.length>7&&trimmed[7]!=="",hasInvariantViolated=trimmed.length>6&&trimmed[6]!=="";if(hasImpactContext&&!hasInvariantViolated)return"base_explorer";if(hasInvariantViolated&&!hasImpactContext)return"micro_lane";if(hasImpactContext&&hasInvariantViolated)return"base_explorer";throw new UnknownFormatFamilyError}function mapFields(fields,family){let trimmed=fields.map((f)=>f.trim()),names=CANDIDATE_FIELDS[family],result={};for(let i=0;i<names.length;i++)result[names[i]]=i<trimmed.length&&trimmed[i]!==""?trimmed[i]:null;if(family==="base_explorer")result.micro_lane=null,result.invariant_violated=null;else result.lane=null,result.impact_context=null;return result}function getRequiredFields(family){return CANDIDATE_FIELDS[family]}function assertNonNullCandidateId(value){if(value===null||value==="")throw Error("Invariant violation: null/empty candidate_id reached candidate builder")}function buildInvocationEnvelope(input,flags,formatFamiliesDetected,candidateCount,parseErrors,malformedRows,cleanAttestationCount=0){return{record_type:"invocation",source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,row_format_version:flags.row_format_version,sessionId:input.sessionId,parentSessionId:input.parentSessionId,...flags.producer?{producer:flags.producer}:{},produced_at:input.produced_at,record_version:RECORD_VERSION,format_families_detected:formatFamiliesDetected,candidate_count:candidateCount,parse_errors:parseErrors,malformed_rows:malformedRows,clean_attestation_count:cleanAttestationCount}}function buildEmptyDiagnostics(input,flags){return{candidate_count:0,parse_errors:0,parse_error_details:[],malformed_rows:0,duplicate_id_count:0,duplicate_id_warnings:[],degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:[],clean_attestation_count:0}}function refusalResult(errorCode,errorMessage,input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0);return{error:errorMessage,error_code:errorCode,candidates:[],invocation_envelope:envelope,diagnostics:buildEmptyDiagnostics(input,flags)}}function detectFormatMismatchHint(text){if(text.trim()==="")return;let severityPattern=/\b(CRITICAL|HIGH|MEDIUM|LOW|INFO)\b/,fileLinePattern=/\b\S+\.[a-z]{1,4}:\d+\b/,hasSeverity=severityPattern.test(text),textForFileLine=text.replace(/\b\w+:\/\/\S*/g,""),hasFileLine=fileLinePattern.test(textForFileLine);if(hasSeverity&&hasFileLine)return"Lane output contains severity keywords and file:line references but no parseable [CANDIDATE] rows. The explorer may have emitted findings in prose format instead of pipe-delimited candidate rows.";if(hasSeverity)return"Lane output contains severity keywords but no parseable [CANDIDATE] rows. The explorer may have emitted findings in an unstructured format.";return}function emptyTextResult(input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0),diagnostics=buildEmptyDiagnostics(input,flags),hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint;return{candidates:[],invocation_envelope:envelope,diagnostics}}function parseCandidates(input,flags){let inputParse=ArtifactInputSchema.safeParse(input);if(!inputParse.success)throw Error(`Invalid ArtifactInput: ${inputParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let flagsParse=ParseFlagsSchema.safeParse(flags);if(!flagsParse.success)throw Error(`Invalid ParseFlags: ${flagsParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let validatedInput=inputParse.data,validatedFlags=flagsParse.data;if(validatedInput.artifact_status==="ref-not-found")return refusalResult("ref-not-found","Artifact reference not found in store",validatedInput,validatedFlags);if(validatedInput.artifact_status==="artifact-corrupted")return refusalResult("artifact-corrupted","Artifact data is corrupted",validatedInput,validatedFlags);if(validatedFlags.degraded&&!validatedFlags.accept_degraded)return refusalResult("degraded-source-refused","Degraded source refused by caller",validatedInput,validatedFlags);if(validatedInput.transcriptIncomplete===!0&&!validatedFlags.accept_partial)return refusalResult("partial-source-refused","Partial transcript refused by caller",validatedInput,validatedFlags);if(validatedInput.text.trim()==="")return emptyTextResult(validatedInput,validatedFlags);return parseText(validatedInput,validatedFlags)}function parseText(input,flags){let lines=removeCandidateCodeFences(input.text).split(`
175
- `),header=selectCandidateHeader(lines);if(header===null)return emptyTextResult(input,flags);let headerIndex=header.lineIndex,headerFamily=header.family??void 0;if(header.markerBearing&&headerFamily===void 0)return refusalResult("invalid-candidate-header","Candidate output must begin with one exact canonical base or micro [CANDIDATE] header",input,flags);if(flags.expected_family!==void 0&&headerFamily!==void 0&&flags.expected_family!==headerFamily)return refusalResult("expected-family-mismatch",`Expected ${flags.expected_family} rows but header declares ${headerFamily}`,input,flags);let parseErrorDetails=[],candidates=[],idCounts=new Map,idFirstRows=new Map,formatFamiliesDetected=new Set,malformedRows=0,currentCandidate=null,pendingClean,cleanErrorCode,cleanErrorMessage;for(let i=headerIndex+1;i<lines.length;i++){let trimmed=lines[i].trim();if(trimmed==="")continue;let fields=splitPipeFields(trimmed);if(fields[0]?.trim()==="[CLEAN]"){let cleanFamily=flags.expected_family??headerFamily,cleanFields=fields.map((field)=>field.trim()),cleanLane=cleanFamily==="micro_lane"?flags.expected_micro_lane:flags.expected_lane,cleanLanes=cleanFamily==="micro_lane"?flags.expected_micro_lanes??(flags.expected_micro_lane?[flags.expected_micro_lane]:void 0):flags.expected_lanes??(flags.expected_lane?[flags.expected_lane]:void 0);if(cleanFamily!==void 0&&cleanFields.length===4&&cleanLane!==void 0&&cleanFields[1]!==cleanLane&&(cleanLanes??[cleanLane]).includes(cleanFields[1]))continue;let cleanAnalysis=cleanFamily?analyzeCleanFields(cleanFields,cleanFamily,cleanLane):void 0;if(pendingClean!==void 0)cleanErrorCode="invalid-clean-attestation",cleanErrorMessage="Only one CLEAN attestation is allowed per artifact";else if(!cleanFamily||!cleanAnalysis)cleanErrorCode="invalid-clean-attestation",cleanErrorMessage="CLEAN attestation is valid only for base_explorer or micro_lane output";else if(!cleanAnalysis.valid)cleanErrorCode=cleanAnalysis.issues.some((issue2)=>["lane","micro_lane"].includes(issue2.field))?cleanFamily==="base_explorer"?"expected-lane-mismatch":"expected-micro-lane-mismatch":"invalid-clean-attestation",cleanErrorMessage=cleanAnalysis.issues.map((issue2)=>`${issue2.field}: ${issue2.message}`).join("; ");else if(cleanFamily==="base_explorer")pendingClean={record_type:"clean_attestation",row_format_family:"base_explorer",row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,extracted_from_partial_source:!1,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,lane:cleanAnalysis.lane,coverage_scope:cleanAnalysis.coverageScope,evidence:cleanAnalysis.evidence};else pendingClean={record_type:"clean_attestation",row_format_family:"micro_lane",row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,extracted_from_partial_source:!1,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,micro_lane:cleanAnalysis.lane,coverage_scope:cleanAnalysis.coverageScope,evidence:cleanAnalysis.evidence};if(cleanErrorCode){parseErrorDetails.push({row_index:i,field:"clean_attestation",message:cleanErrorMessage??"Invalid CLEAN attestation"}),malformedRows++;continue}if(flags.degraded||input.transcriptIncomplete===!0){cleanErrorCode="untrusted-clean-attestation",cleanErrorMessage="CLEAN attestation cannot come from a degraded or partial artifact",parseErrorDetails.push({row_index:i,field:"clean_attestation",message:cleanErrorMessage}),malformedRows++;continue}continue}let hadCandidateMarker=fields[0]?.trim()==="[CANDIDATE]";if(hadCandidateMarker)fields=fields.slice(1);if(fields.length<CANDIDATE_FIELD_COUNT){if(isCandidateLookingShortRow(fields,flags,hadCandidateMarker)){parseErrorDetails.push({row_index:i,field:"row",message:"Structurally short [CANDIDATE] row must be a full candidate or CLEAN attestation, not continuation text"}),malformedRows++;continue}if(currentCandidate){let prev=currentCandidate.evidence_summary??"";currentCandidate.evidence_summary=`${prev}
176
- ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE_FIELD_COUNT),rowFamily;if(flags.expected_family??headerFamily)rowFamily=flags.expected_family??headerFamily;else try{rowFamily=detectRowFormatFamily(rowFields)}catch(e){if(e instanceof UnknownFormatFamilyError){malformedRows++;continue}throw e}let rowHasImpact=rowFields[7].trim()!=="",rowHasInvariant=rowFields[6].trim()!=="";if(rowHasImpact&&rowHasInvariant&&rowFamily==="base_explorer"&&flags.expected_family===void 0&&headerFamily===void 0)parseErrorDetails.push({row_index:i,field:"row",message:"Both format-family discriminators present; defaulting to base_explorer"});let mapped=mapFields(rowFields,rowFamily);if(rowFamily==="base_explorer"&&flags.expected_lane!==void 0&&mapped.lane!==flags.expected_lane){if(mapped.lane!==null&&(flags.expected_lanes??[flags.expected_lane]).includes(mapped.lane))continue;parseErrorDetails.push({row_index:i,field:"lane",message:`Expected lane ${candidateDiagnosticPreview(flags.expected_lane)}, received ${candidateDiagnosticPreview(mapped.lane??"<missing>")}`}),malformedRows++;continue}if(rowFamily==="micro_lane"&&flags.expected_micro_lane!==void 0&&mapped.micro_lane!==flags.expected_micro_lane){if(mapped.micro_lane!==null&&(flags.expected_micro_lanes??[flags.expected_micro_lane]).includes(mapped.micro_lane))continue;parseErrorDetails.push({row_index:i,field:"micro_lane",message:`Expected micro_lane ${candidateDiagnosticPreview(flags.expected_micro_lane)}, received ${candidateDiagnosticPreview(mapped.micro_lane??"<missing>")}`}),malformedRows++;continue}let semanticAnalysis=analyzeCandidateFields(fields,rowFamily);if(!semanticAnalysis.valid){for(let issue2 of semanticAnalysis.issues)parseErrorDetails.push({row_index:i,field:issue2.field,message:issue2.message});malformedRows++;continue}let requiredFields=rowFamily==="base_explorer"?getRequiredFields("base_explorer"):getRequiredFields("micro_lane"),rowMalformed=!1;for(let field of requiredFields){let value=mapped[field];if(field==="candidate_id"){if(value===null||value===""){rowMalformed=!0;break}}else if(value===null)parseErrorDetails.push({row_index:i,field,message:`Missing required field: ${field}`})}if(rowMalformed){malformedRows++;continue}assertNonNullCandidateId(mapped.candidate_id);let candidateId=mapped.candidate_id,candidate={record_type:"candidate",row_format_family:rowFamily,row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,extracted_from_partial_source:!!(input.transcriptIncomplete||flags.degraded),candidate_id:candidateId,lane:mapped.lane,micro_lane:mapped.micro_lane,severity:mapped.severity,category:mapped.category,file_line:mapped.file_line,claim:mapped.claim,evidence_summary:mapped.evidence_summary,impact_context:mapped.impact_context,invariant_violated:mapped.invariant_violated,confidence:mapped.confidence},cid=candidate.candidate_id;if(idCounts.set(cid,(idCounts.get(cid)??0)+1),!idFirstRows.has(cid))idFirstRows.set(cid,i);formatFamiliesDetected.add(rowFamily),candidates.push(candidate),currentCandidate=candidate}let duplicateIdWarnings=[],duplicateIdCount=0;for(let[id,count]of idCounts)if(count>1)duplicateIdCount++,duplicateIdWarnings.push({candidate_id:candidateDiagnosticPreview(id),occurrences:count}),parseErrorDetails.push({row_index:idFirstRows.get(id)??-1,field:"candidate_id",message:`Duplicate candidate_id: "${candidateDiagnosticPreview(id)}" appears ${count} times`});if(pendingClean&&candidates.length>0)cleanErrorCode="conflicting-clean-attestation",cleanErrorMessage="CLEAN attestation cannot appear with candidate rows",parseErrorDetails.push({row_index:headerIndex,field:"clean_attestation",message:cleanErrorMessage});if(pendingClean&&!cleanErrorCode&&(malformedRows>0||parseErrorDetails.length>0))cleanErrorCode="untrusted-clean-attestation",cleanErrorMessage="CLEAN attestation requires zero malformed rows and zero parse errors",parseErrorDetails.push({row_index:headerIndex,field:"clean_attestation",message:cleanErrorMessage});let cleanAttestation=pendingClean&&!cleanErrorCode&&candidates.length===0?pendingClean:void 0;if(cleanAttestation)formatFamiliesDetected.add(cleanAttestation.row_format_family);let acceptedCandidates=candidates,parseErrors=parseErrorDetails.length,envelope=buildInvocationEnvelope(input,flags,Array.from(formatFamiliesDetected),acceptedCandidates.length,parseErrors,malformedRows,cleanAttestation?1:0),diagnostics={candidate_count:acceptedCandidates.length,parse_errors:parseErrors,parse_error_details:parseErrorDetails,malformed_rows:malformedRows,duplicate_id_count:duplicateIdCount,duplicate_id_warnings:duplicateIdWarnings,degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:Array.from(formatFamiliesDetected),clean_attestation_count:cleanAttestation?1:0};if(acceptedCandidates.length===0&&!cleanAttestation){let hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint}return{...cleanErrorCode?{error:cleanErrorMessage??"Invalid CLEAN attestation",error_code:cleanErrorCode}:{},candidates:acceptedCandidates,...cleanAttestation?{clean_attestation:cleanAttestation}:{},invocation_envelope:envelope,diagnostics}}function parseAndPersist(input,flags,options){let normalizedInput=flags.expected_family?{...input,text:normalizeCandidateArtifact(input.text,flags.expected_family).text}:input,result=parseCandidates(normalizedInput,flags);try{appendToSidecar(options,input.batchId,result.invocation_envelope,result.candidates,result.clean_attestation)}catch(error49){let message=error49 instanceof Error?error49.message:String(error49);return{...result,sidecar_write_error:message}}return result}var ArtifactInputSchema,ParseFlagsSchema,RECORD_VERSION,UnknownFormatFamilyError;var init_candidate_parser=__esm(()=>{init_zod();init_candidate_contract();init_candidate_sidecar_store();ArtifactInputSchema=exports_external.object({output_ref:exports_external.string().min(1,"output_ref must be a non-empty string"),batchId:exports_external.string().min(1,"batchId must be a non-empty string"),laneId:exports_external.string().min(1,"laneId must be a non-empty string"),agent:exports_external.string().min(1,"agent must be a non-empty string"),role:exports_external.string().min(1,"role must be a non-empty string"),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/,"digest must be a SHA-256 hex string"),text:exports_external.string(),transcriptIncomplete:exports_external.boolean().optional(),artifact_status:exports_external.enum(["ok","ref-not-found","artifact-corrupted"]),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),produced_at:exports_external.string().min(1,"produced_at must be a non-empty string")}).strict(),ParseFlagsSchema=exports_external.object({accept_partial:exports_external.boolean(),accept_degraded:exports_external.boolean(),degraded:exports_external.boolean(),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional(),expected_lane:exports_external.string().trim().min(1).max(120).optional(),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional(),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional(),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional()}).strict().superRefine((value,context)=>{for(let issue2 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue2.field],message:issue2.message})}),RECORD_VERSION={major:1,minor:1};UnknownFormatFamilyError=class UnknownFormatFamilyError extends Error{constructor(){super("Unknown format family: neither impact_context nor invariant_violated present");this.name="UnknownFormatFamilyError"}}});import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync2,renameSync,unlinkSync,writeFileSync}from"node:fs";import*as path7 from"node:path";function storeLaneOutput(directory,input,now=Date.now){let bytes=Buffer.byteLength(input.text,"utf-8"),digest=digestText(input.text);if(bytes>MAX_LANE_OUTPUT_STORED_BYTES)return{digest,chars:input.text.length,bytes,degraded:!0,error:`lane output exceeds ${MAX_LANE_OUTPUT_STORED_BYTES} byte storage limit`};let batchDigest=digestText(input.batchId),laneDigest=digestText(input.laneId),ref=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`,relPath=laneOutputRelativePath(ref),absPath=validateSwarmPath(directory,relPath),timestamp=new Date(now()).toISOString();try{if(existsSync3(absPath)){let existing=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")));if(existing.success&&hasValidArtifactIntegrity(existing.data,ref)&&artifactIdentityMatchesInput(existing.data,input))return{ref,digest,chars:existing.data.chars,bytes:existing.data.bytes,degraded:!1};if(existing.success&&hasValidArtifactIntegrity(existing.data,ref))return{digest,chars:input.text.length,bytes,degraded:!0,error:"lane output ref collision has incompatible agent/session provenance"}}let artifact={schemaVersion:LANE_OUTPUT_SCHEMA_VERSION,ref,batchId:input.batchId,laneId:input.laneId,agent:input.agent,role:input.role,...input.sessionId?{sessionId:input.sessionId}:{},...input.parentSessionId?{parentSessionId:input.parentSessionId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.prHeadSha?{prHeadSha:input.prHeadSha}:{},...input.gitHead?{gitHead:input.gitHead}:{},...input.revisionDigest?{revisionDigest:input.revisionDigest}:{},...input.scope?{scope:input.scope}:{},source:input.source,text:input.text,chars:input.text.length,bytes,digest,...input.messageCount!==void 0?{messageCount:input.messageCount}:{},...input.transcriptIncomplete!==void 0?{transcriptIncomplete:input.transcriptIncomplete}:{},createdAt:timestamp,updatedAt:timestamp};return writeAtomicJson(absPath,artifact),{ref,digest,chars:artifact.chars,bytes:artifact.bytes,degraded:!1}}catch(error49){return{digest,chars:input.text.length,bytes,degraded:!0,error:error49 instanceof Error?error49.message:"failed to store lane output artifact"}}}function readLaneOutput(directory,ref){if(!REF_RE.test(ref))return null;let absPath=validateSwarmPath(directory,laneOutputRelativePath(ref));if(!existsSync3(absPath))return null;let parsed;try{parsed=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")))}catch{return null}if(!parsed.success||!hasValidArtifactIntegrity(parsed.data,ref))return null;return{artifact:parsed.data}}function buildLaneOutputPreview(args2){let{text,ref,degraded,maxChars}=args2;if(!(text.length>maxChars)&&!degraded)return{output:text,output_chars:text.length,output_truncated:!1};let marker=buildPreviewMarker({omittedChars:Math.max(0,text.length-maxChars),ref,degraded:degraded===!0});if(text.length<=maxChars&&degraded)return{output:`${text}${marker}`,output_chars:text.length,output_truncated:!1};let budget=Math.max(0,maxChars-marker.length),headChars=Math.ceil(budget/2),tailChars=Math.floor(budget/2),head=text.slice(0,headChars),tail=tailChars>0?text.slice(text.length-tailChars):"";return{output:`${head}${marker}${tail}`,output_chars:text.length,output_truncated:!0}}function paginateLaneOutput(text,offset,limit){let lines=text.length===0?[]:text.split(`
177
+ `),header=selectCandidateHeader(lines);if(header===null)return emptyTextResult(input,flags);let headerIndex=header.lineIndex,headerFamily=header.family??void 0;if(header.markerBearing&&headerFamily===void 0)return refusalResult("invalid-candidate-header","Candidate output must begin with one exact canonical base or micro [CANDIDATE] header",input,flags);if(flags.expected_family!==void 0&&headerFamily!==void 0&&flags.expected_family!==headerFamily)return refusalResult("expected-family-mismatch",`Expected ${flags.expected_family} rows but header declares ${headerFamily}`,input,flags);let parseErrorDetails=[],candidates=[],idCounts=new Map,idFirstRows=new Map,formatFamiliesDetected=new Set,malformedRows=0,currentCandidate=null,pendingClean,cleanErrorCode,cleanErrorMessage;for(let i=headerIndex+1;i<lines.length;i++){let trimmed=lines[i].trim();if(trimmed==="")continue;let fields=splitPipeFields(trimmed);if(fields[0]?.trim()==="[CLEAN]"){let cleanFamily=flags.expected_family??headerFamily,cleanFields=fields.map((field)=>field.trim()),cleanLane=cleanFamily==="micro_lane"?flags.expected_micro_lane:flags.expected_lane,cleanLanes=cleanFamily==="micro_lane"?flags.expected_micro_lanes??(flags.expected_micro_lane?[flags.expected_micro_lane]:void 0):flags.expected_lanes??(flags.expected_lane?[flags.expected_lane]:void 0);if(cleanFamily!==void 0&&cleanFields.length===4&&cleanLane!==void 0&&cleanFields[1]!==cleanLane&&(cleanLanes??[cleanLane]).includes(cleanFields[1]))continue;let cleanAnalysis=cleanFamily?analyzeCleanFields(cleanFields,cleanFamily,cleanLane):void 0;if(pendingClean!==void 0&&cleanAnalysis?.valid===!0&&cleanAnalysis.lane!==(pendingClean.row_format_family==="base_explorer"?pendingClean.lane:pendingClean.micro_lane))continue;if(pendingClean!==void 0)cleanErrorCode="invalid-clean-attestation",cleanErrorMessage="Only one CLEAN attestation is allowed per artifact";else if(!cleanFamily||!cleanAnalysis)cleanErrorCode="invalid-clean-attestation",cleanErrorMessage="CLEAN attestation is valid only for base_explorer or micro_lane output";else if(!cleanAnalysis.valid)cleanErrorCode=cleanAnalysis.issues.some((issue2)=>["lane","micro_lane"].includes(issue2.field))?cleanFamily==="base_explorer"?"expected-lane-mismatch":"expected-micro-lane-mismatch":"invalid-clean-attestation",cleanErrorMessage=cleanAnalysis.issues.map((issue2)=>`${issue2.field}: ${issue2.message}`).join("; ");else if(cleanFamily==="base_explorer")pendingClean={record_type:"clean_attestation",row_format_family:"base_explorer",row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,extracted_from_partial_source:!1,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,lane:cleanAnalysis.lane,coverage_scope:cleanAnalysis.coverageScope,evidence:cleanAnalysis.evidence};else pendingClean={record_type:"clean_attestation",row_format_family:"micro_lane",row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,extracted_from_partial_source:!1,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,micro_lane:cleanAnalysis.lane,coverage_scope:cleanAnalysis.coverageScope,evidence:cleanAnalysis.evidence};if(cleanErrorCode){parseErrorDetails.push({row_index:i,field:"clean_attestation",message:cleanErrorMessage??"Invalid CLEAN attestation"}),malformedRows++;continue}if(flags.degraded||input.transcriptIncomplete===!0){cleanErrorCode="untrusted-clean-attestation",cleanErrorMessage="CLEAN attestation cannot come from a degraded or partial artifact",parseErrorDetails.push({row_index:i,field:"clean_attestation",message:cleanErrorMessage}),malformedRows++;continue}continue}let hadCandidateMarker=fields[0]?.trim()==="[CANDIDATE]";if(hadCandidateMarker)fields=fields.slice(1);if(fields.length<CANDIDATE_FIELD_COUNT){if(isCandidateLookingShortRow(fields,flags,hadCandidateMarker)){parseErrorDetails.push({row_index:i,field:"row",message:"Structurally short [CANDIDATE] row must be a full candidate or CLEAN attestation, not continuation text"}),malformedRows++;continue}if(currentCandidate){let prev=currentCandidate.evidence_summary??"";currentCandidate.evidence_summary=`${prev}
178
+ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE_FIELD_COUNT),rowFamily;if(flags.expected_family??headerFamily)rowFamily=flags.expected_family??headerFamily;else try{rowFamily=detectRowFormatFamily(rowFields)}catch(e){if(e instanceof UnknownFormatFamilyError){malformedRows++;continue}throw e}let rowHasImpact=rowFields[7].trim()!=="",rowHasInvariant=rowFields[6].trim()!=="";if(rowHasImpact&&rowHasInvariant&&rowFamily==="base_explorer"&&flags.expected_family===void 0&&headerFamily===void 0)parseErrorDetails.push({row_index:i,field:"row",message:"Both format-family discriminators present; defaulting to base_explorer"});let mapped=mapFields(rowFields,rowFamily);if(rowFamily==="base_explorer"&&flags.expected_lane!==void 0&&mapped.lane!==flags.expected_lane){if(mapped.lane!==null&&(flags.expected_lanes??[flags.expected_lane]).includes(mapped.lane))continue;parseErrorDetails.push({row_index:i,field:"lane",message:`Expected lane ${candidateDiagnosticPreview(flags.expected_lane)}, received ${candidateDiagnosticPreview(mapped.lane??"<missing>")}`}),malformedRows++;continue}if(rowFamily==="micro_lane"&&flags.expected_micro_lane!==void 0&&mapped.micro_lane!==flags.expected_micro_lane){if(mapped.micro_lane!==null&&(flags.expected_micro_lanes??[flags.expected_micro_lane]).includes(mapped.micro_lane))continue;parseErrorDetails.push({row_index:i,field:"micro_lane",message:`Expected micro_lane ${candidateDiagnosticPreview(flags.expected_micro_lane)}, received ${candidateDiagnosticPreview(mapped.micro_lane??"<missing>")}`}),malformedRows++;continue}let semanticAnalysis=analyzeCandidateFields(fields,rowFamily);if(!semanticAnalysis.valid){for(let issue2 of semanticAnalysis.issues)parseErrorDetails.push({row_index:i,field:issue2.field,message:issue2.message});malformedRows++;continue}let requiredFields=rowFamily==="base_explorer"?getRequiredFields("base_explorer"):getRequiredFields("micro_lane"),rowMalformed=!1;for(let field of requiredFields){let value=mapped[field];if(field==="candidate_id"){if(value===null||value===""){rowMalformed=!0;break}}else if(value===null)parseErrorDetails.push({row_index:i,field,message:`Missing required field: ${field}`})}if(rowMalformed){malformedRows++;continue}assertNonNullCandidateId(mapped.candidate_id);let candidateId=mapped.candidate_id,candidate={record_type:"candidate",row_format_family:rowFamily,row_format_version:flags.row_format_version,record_version:RECORD_VERSION,source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,sessionId:input.sessionId,parentSessionId:input.parentSessionId,producer:flags.producer,extracted_from_partial_source:!!(input.transcriptIncomplete||flags.degraded),candidate_id:candidateId,lane:mapped.lane,micro_lane:mapped.micro_lane,severity:mapped.severity,category:mapped.category,file_line:mapped.file_line,claim:mapped.claim,evidence_summary:mapped.evidence_summary,impact_context:mapped.impact_context,invariant_violated:mapped.invariant_violated,confidence:mapped.confidence},cid=candidate.candidate_id;if(idCounts.set(cid,(idCounts.get(cid)??0)+1),!idFirstRows.has(cid))idFirstRows.set(cid,i);formatFamiliesDetected.add(rowFamily),candidates.push(candidate),currentCandidate=candidate}let duplicateIdWarnings=[],duplicateIdCount=0;for(let[id,count]of idCounts)if(count>1)duplicateIdCount++,duplicateIdWarnings.push({candidate_id:candidateDiagnosticPreview(id),occurrences:count}),parseErrorDetails.push({row_index:idFirstRows.get(id)??-1,field:"candidate_id",message:`Duplicate candidate_id: "${candidateDiagnosticPreview(id)}" appears ${count} times`});let pendingCleanLane=pendingClean?pendingClean.row_format_family==="base_explorer"?pendingClean.lane:pendingClean.micro_lane:null;if(pendingClean&&pendingCleanLane!==null){if(candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===pendingCleanLane))cleanErrorCode="conflicting-clean-attestation",cleanErrorMessage=`CLEAN attestation cannot appear with candidate rows for the same lane (${pendingCleanLane})`,parseErrorDetails.push({row_index:headerIndex,field:"clean_attestation",message:cleanErrorMessage})}if(pendingClean&&!cleanErrorCode&&(malformedRows>0||parseErrorDetails.length>0))cleanErrorCode="untrusted-clean-attestation",cleanErrorMessage="CLEAN attestation requires zero malformed rows and zero parse errors",parseErrorDetails.push({row_index:headerIndex,field:"clean_attestation",message:cleanErrorMessage});let cleanAttestation=pendingClean&&!cleanErrorCode?pendingClean:void 0;if(cleanAttestation)formatFamiliesDetected.add(cleanAttestation.row_format_family);let acceptedCandidates=candidates,parseErrors=parseErrorDetails.length,envelope=buildInvocationEnvelope(input,flags,Array.from(formatFamiliesDetected),acceptedCandidates.length,parseErrors,malformedRows,cleanAttestation?1:0),diagnostics={candidate_count:acceptedCandidates.length,parse_errors:parseErrors,parse_error_details:parseErrorDetails,malformed_rows:malformedRows,duplicate_id_count:duplicateIdCount,duplicate_id_warnings:duplicateIdWarnings,degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:Array.from(formatFamiliesDetected),clean_attestation_count:cleanAttestation?1:0};if(acceptedCandidates.length===0&&!cleanAttestation){let hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint}return{...cleanErrorCode?{error:cleanErrorMessage??"Invalid CLEAN attestation",error_code:cleanErrorCode}:{},candidates:acceptedCandidates,...cleanAttestation?{clean_attestation:cleanAttestation}:{},invocation_envelope:envelope,diagnostics}}function parseAndPersist(input,flags,options){let normalizedInput=flags.expected_family?{...input,text:normalizeCandidateArtifact(input.text,flags.expected_family).text}:input,result=parseCandidates(normalizedInput,flags);try{appendToSidecar(options,input.batchId,result.invocation_envelope,result.candidates,result.clean_attestation)}catch(error49){let message=error49 instanceof Error?error49.message:String(error49);return{...result,sidecar_write_error:message}}return result}var ArtifactInputSchema,ParseFlagsSchema,RECORD_VERSION,UnknownFormatFamilyError;var init_candidate_parser=__esm(()=>{init_zod();init_candidate_contract();init_candidate_sidecar_store();ArtifactInputSchema=exports_external.object({output_ref:exports_external.string().min(1,"output_ref must be a non-empty string"),batchId:exports_external.string().min(1,"batchId must be a non-empty string"),laneId:exports_external.string().min(1,"laneId must be a non-empty string"),agent:exports_external.string().min(1,"agent must be a non-empty string"),role:exports_external.string().min(1,"role must be a non-empty string"),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/,"digest must be a SHA-256 hex string"),text:exports_external.string(),transcriptIncomplete:exports_external.boolean().optional(),artifact_status:exports_external.enum(["ok","ref-not-found","artifact-corrupted"]),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),produced_at:exports_external.string().min(1,"produced_at must be a non-empty string")}).strict(),ParseFlagsSchema=exports_external.object({accept_partial:exports_external.boolean(),accept_degraded:exports_external.boolean(),degraded:exports_external.boolean(),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),expected_family:exports_external.enum(["base_explorer","micro_lane"]).optional(),expected_lane:exports_external.string().trim().min(1).max(120).optional(),expected_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional(),expected_micro_lane:exports_external.string().trim().min(1).max(120).optional(),expected_micro_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional()}).strict().superRefine((value,context)=>{for(let issue2 of analyzeCandidateLaneContext(value))context.addIssue({code:exports_external.ZodIssueCode.custom,path:[issue2.field],message:issue2.message})}),RECORD_VERSION={major:1,minor:1};UnknownFormatFamilyError=class UnknownFormatFamilyError extends Error{constructor(){super("Unknown format family: neither impact_context nor invariant_violated present");this.name="UnknownFormatFamilyError"}}});import{createHash as createHash2}from"node:crypto";import{existsSync as existsSync3,mkdirSync as mkdirSync2,readFileSync as readFileSync2,renameSync,unlinkSync,writeFileSync}from"node:fs";import*as path7 from"node:path";function storeLaneOutput(directory,input,now=Date.now){let bytes=Buffer.byteLength(input.text,"utf-8"),digest=digestText(input.text);if(bytes>MAX_LANE_OUTPUT_STORED_BYTES)return{digest,chars:input.text.length,bytes,degraded:!0,error:`lane output exceeds ${MAX_LANE_OUTPUT_STORED_BYTES} byte storage limit`};let batchDigest=digestText(input.batchId),laneDigest=digestText(input.laneId),ref=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`,relPath=laneOutputRelativePath(ref),absPath=validateSwarmPath(directory,relPath),timestamp=new Date(now()).toISOString();try{if(existsSync3(absPath)){let existing=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")));if(existing.success&&hasValidArtifactIntegrity(existing.data,ref)&&artifactIdentityMatchesInput(existing.data,input))return{ref,digest,chars:existing.data.chars,bytes:existing.data.bytes,degraded:!1};if(existing.success&&hasValidArtifactIntegrity(existing.data,ref))return{digest,chars:input.text.length,bytes,degraded:!0,error:"lane output ref collision has incompatible agent/session provenance"}}let artifact={schemaVersion:LANE_OUTPUT_SCHEMA_VERSION,ref,batchId:input.batchId,laneId:input.laneId,agent:input.agent,role:input.role,...input.sessionId?{sessionId:input.sessionId}:{},...input.parentSessionId?{parentSessionId:input.parentSessionId}:{},...input.mode?{mode:input.mode}:{},...input.workflowLane?{workflowLane:input.workflowLane}:{},...input.prHeadSha?{prHeadSha:input.prHeadSha}:{},...input.gitHead?{gitHead:input.gitHead}:{},...input.revisionDigest?{revisionDigest:input.revisionDigest}:{},...input.scope?{scope:input.scope}:{},source:input.source,text:input.text,chars:input.text.length,bytes,digest,...input.messageCount!==void 0?{messageCount:input.messageCount}:{},...input.transcriptIncomplete!==void 0?{transcriptIncomplete:input.transcriptIncomplete}:{},createdAt:timestamp,updatedAt:timestamp};return writeAtomicJson(absPath,artifact),{ref,digest,chars:artifact.chars,bytes:artifact.bytes,degraded:!1}}catch(error49){return{digest,chars:input.text.length,bytes,degraded:!0,error:error49 instanceof Error?error49.message:"failed to store lane output artifact"}}}function readLaneOutput(directory,ref){if(!REF_RE.test(ref))return null;let absPath=validateSwarmPath(directory,laneOutputRelativePath(ref));if(!existsSync3(absPath))return null;let parsed;try{parsed=LaneOutputArtifactSchema.safeParse(JSON.parse(readFileSync2(absPath,"utf-8")))}catch{return null}if(!parsed.success||!hasValidArtifactIntegrity(parsed.data,ref))return null;return{artifact:parsed.data}}function buildLaneOutputPreview(args2){let{text,ref,degraded,maxChars}=args2;if(!(text.length>maxChars)&&!degraded)return{output:text,output_chars:text.length,output_truncated:!1};let marker=buildPreviewMarker({omittedChars:Math.max(0,text.length-maxChars),ref,degraded:degraded===!0});if(text.length<=maxChars&&degraded)return{output:`${text}${marker}`,output_chars:text.length,output_truncated:!1};let budget=Math.max(0,maxChars-marker.length),headChars=Math.ceil(budget/2),tailChars=Math.floor(budget/2),head=text.slice(0,headChars),tail=tailChars>0?text.slice(text.length-tailChars):"";return{output:`${head}${marker}${tail}`,output_chars:text.length,output_truncated:!0}}function paginateLaneOutput(text,offset,limit){let lines=text.length===0?[]:text.split(`
177
179
  `),totalLines=lines.length,startLine=Math.max(0,offset);if(startLine>=totalLines)return{totalLines,startLine,endLine:totalLines,content:"",exhausted:!0};let endLine=Math.min(startLine+limit,totalLines);return{totalLines,startLine,endLine,content:lines.slice(startLine,endLine).join(`
178
180
  `),exhausted:!1}}function buildPreviewMarker(args2){let retrieval=args2.ref?` retrieve_lane_output ref=${args2.ref} for full output.`:" no full output artifact is available; treat this lane as degraded.";return`
179
181
  [... lane output preview omitted middle content.${args2.degraded?" Artifact storage degraded.":""}${retrieval} ...]
@@ -184,7 +186,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
184
186
  ---
185
187
  `).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord(directory,next),acknowledged+=1}}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}function findByBatchId(directory,batchId,opts){if(!batchId)return[];return readDelegations(directory).filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function sweepStaleLocked(directory,timeoutMs,now){let swept=0;for(let record2 of readDelegations(directory)){if(record2.status!=="pending"&&record2.status!=="running"&&record2.status!=="ingestion_error")continue;if(now-record2.updatedAt<=timeoutMs)continue;appendRecord(directory,{...record2,status:"stale",updatedAt:now}),swept+=1}return swept}async function sweepStaleDelegations(directory,timeoutMs){if(!timeoutMs||timeoutMs<=0)return 0;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>sweepStaleLocked(directory,timeoutMs,Date.now()))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}function fallbackRelativePath(correlationId){let digest=createHash5("sha256").update(correlationId).digest("hex");return path11.join(BACKGROUND_DELEGATION_FALLBACK_DIR,`${digest}.json`)}function fallbackPath(directory,correlationId){return validateSwarmPath(directory,fallbackRelativePath(correlationId))}function fallbackDirectoryPath(directory){return path11.dirname(validateSwarmPath(directory,path11.join(BACKGROUND_DELEGATION_FALLBACK_DIR,".containment-anchor")))}async function readFallbackFile(directory,correlationId){for(let attempt=0;attempt<5;attempt++)try{let raw=await fs7.promises.readFile(fallbackPath(directory,correlationId),"utf-8"),parsedJson=JSON.parse(raw),parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success||parsed.data.correlationId!==correlationId)return null;return parsed.data}catch(err){if(err.code==="ENOENT"&&attempt<4){await new Promise((resolve7)=>setTimeout(resolve7,10));continue}return null}return null}async function readDelegationFallback(directory,correlationId){if(!correlationId)return null;return readFallbackFile(directory,correlationId)}async function listDelegationFallbacks(directory){let entries;try{entries=fs7.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).slice(0,MAX_LIVE_BACKGROUND_FALLBACKS)}catch{return[]}let artifacts=[];for(let entry of entries)try{let raw=await fs7.promises.readFile(path11.join(fallbackDirectoryPath(directory),entry.name),"utf-8"),parsed=FallbackArtifactSchema.safeParse(JSON.parse(raw));if(parsed.success)artifacts.push(parsed.data)}catch{}return artifacts}async function scanDelegationFallbacksForRecovery(directory){let fallbackDir,entries;try{fallbackDir=fallbackDirectoryPath(directory),entries=fs7.readdirSync(fallbackDir,{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background fallback directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_LIVE_BACKGROUND_FALLBACKS)return{status:"uncertain",reason:`background fallback owner count exceeds the ${MAX_LIVE_BACKGROUND_FALLBACKS}-artifact safety bound`};let artifacts=[];for(let entry of entries){let artifactPath=path11.join(fallbackDir,entry.name),raw;try{if(fs7.statSync(artifactPath).size>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" exceeds the recovery size bound`};raw=await fs7.promises.readFile(artifactPath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background fallback artifact "${entry.name}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" changed beyond the recovery size bound`};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has malformed JSON`}}let parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has an invalid owner record`};artifacts.push(parsed.data)}return{status:"ok",owners:artifacts}}function countFallbackFiles(directory){try{return fs7.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).length}catch(err){if(err.code==="ENOENT")return 0;return MAX_LIVE_BACKGROUND_FALLBACKS}}async function writeDelegationFallback(directory,input,options={}){let now=Date.now(),record2={...buildPendingRecord(input,now),schemaVersion:3},artifact={schemaVersion:1,correlationId:input.correlationId,createdAt:now,record:record2},parsed=FallbackArtifactSchema.safeParse(artifact);if(!parsed.success)return null;let requestedCap=Math.floor(Math.max(1,options.maxLive??MAX_LIVE_BACKGROUND_FALLBACKS)),maxLive=Math.min(requestedCap,MAX_LIVE_BACKGROUND_FALLBACKS);try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let existing=await readFallbackFile(directory,input.correlationId);if(existing)return samePendingRecord(existing.record,parsed.data.record)?existing:null;if(countFallbackFiles(directory)>=maxLive)return null;let absPath=fallbackPath(directory,input.correlationId);return fs7.mkdirSync(path11.dirname(absPath),{recursive:!0}),await bunWrite(absPath,`${JSON.stringify(parsed.data)}
186
188
  `),parsed.data})}catch(err){return warn(`[background] writeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}async function removeDelegationFallback(directory,correlationId){if(!correlationId)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{try{return await fs7.promises.unlink(fallbackPath(directory,correlationId)),!0}catch(err){return err.code==="ENOENT"}})}catch(err){return warn(`[background] removeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function findDelegationForCompletion(directory,correlationId){if(!correlationId)return null;let primary=findByCorrelationId(directory,correlationId);if(primary)return{source:"primary",record:primary};let fallback=await readDelegationFallback(directory,correlationId);return fallback?{source:"fallback",record:fallback.record,fallback}:null}function samePromotionIdentity(primary,fallback){return primary.correlationId===fallback.correlationId&&primary.subagentSessionId===fallback.subagentSessionId&&primary.parentSessionId===fallback.parentSessionId&&primary.callID===fallback.callID&&primary.planTaskId===fallback.planTaskId&&primary.coderReservationId===fallback.coderReservationId&&sameJson(primary.worktree??null,fallback.worktree??null)&&sameJson(primary.taskChangeContext??null,fallback.taskChangeContext??null)}function samePendingRecord(left,right){let{createdAt:_leftCreatedAt,updatedAt:_leftUpdatedAt,...leftIdentity}=left,{createdAt:_rightCreatedAt,updatedAt:_rightUpdatedAt,...rightIdentity}=right;return sameJson(leftIdentity,rightIdentity)}async function promoteDelegationFallback(directory,correlationId){if(!correlationId)return null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT,FALLBACK_LOCK_TASK,async()=>{let fallback=await readFallbackFile(directory,correlationId);if(!fallback){let primary=findByCorrelationId(directory,correlationId);return primary?{source:"primary",record:primary}:null}let promoted=null;if(await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let current=findByCorrelationId(directory,correlationId);if(current){if(samePromotionIdentity(current,fallback.record))promoted=current;return}appendRecord(directory,fallback.record),promoted=fallback.record}),!promoted)return null;try{await fs7.promises.unlink(fallbackPath(directory,correlationId))}catch(err){if(err.code!=="ENOENT")return null}return{source:"primary",record:promoted}})}catch(err){return warn(`[background] promoteDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}function reservationStorePath(directory){return validateSwarmPath(directory,BACKGROUND_CODER_RESERVATIONS_FILE)}function buildBackgroundCoderReservationId(input){let ownerIdentity=input.planTaskId===null?["call",input.parentSessionId,input.callID]:["task",input.parentSessionId,input.planTaskId];return`bgcr1:${createHash5("sha256").update(JSON.stringify(ownerIdentity)).digest("hex")}`}function scanBackgroundCoderReservationsForAdmission(directory){let absolutePath,raw;try{if(absolutePath=reservationStorePath(directory),fs7.statSync(absolutePath).size>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:`background coder reservation store exceeds the ${MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES}-byte safety bound`};raw=fs7.readFileSync(absolutePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return{status:"ok",reservations:[]};return{status:"uncertain",reason:`background coder reservation store is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:"background coder reservation store changed beyond its safety bound"};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:"background coder reservation store contains malformed JSON"}}let parsed=BackgroundCoderReservationStoreSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:"background coder reservation store failed strict schema validation"};return{status:"ok",reservations:parsed.data.reservations}}async function writeBackgroundCoderReservations(directory,reservations){let parsed=BackgroundCoderReservationStoreSchema.safeParse({schemaVersion:1,reservations});if(!parsed.success)return!1;try{return await bunWrite(reservationStorePath(directory),`${JSON.stringify(parsed.data)}
187
- `),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64)return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound")return current.correlationId===input.correlationId?current:null;let next={...current,state:"bound",correlationId:input.correlationId,updatedAt:input.now??Date.now()},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_LEDGER_BYTES=4194304,MAX_RECOVERY_FALLBACK_BYTES=1048576,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();init_logger();ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2),exports_external.literal(3)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})})});import{createHash as createHash6}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash6("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED")}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema)}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals9});import*as child_process from"node:child_process";import{createHash as createHash7}from"node:crypto";import*as fs8 from"node:fs";import*as path12 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals9.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals9.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals9.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals9.spawnSync("git",["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
189
+ `),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64)return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound")return current.correlationId===input.correlationId?current:null;let next={...current,state:"bound",correlationId:input.correlationId,updatedAt:input.now??Date.now()},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,MAX_BACKGROUND_DELEGATION_GENERATION=1e6,MAX_RECOVERY_LEDGER_BYTES=4194304,MAX_RECOVERY_FALLBACK_BYTES=1048576,STORE_LOCK_AGENT="background",STORE_LOCK_TASK="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema,FallbackArtifactSchema,MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152;var init_pending_delegations=__esm(()=>{init_zod();init_lock();init_utils2();init_bun_compat();init_logger();ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2),exports_external.literal(3)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict(),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})})});import{createHash as createHash6}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows,coverage_degradations:input.coverage_degradations??[]})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash6("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows,coverageDegradations=[]){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED"),coverageDegradations}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows,receipt.coverage_degradations)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,TriggerCoverageDegradationSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),TriggerCoverageDegradationSchema=exports_external.object({trigger_id:TriggerIdSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1),reason:exports_external.string().trim().min(1)}).strict(),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema),coverage_degradations:exports_external.array(TriggerCoverageDegradationSchema).default([])}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals9});import*as child_process from"node:child_process";import{createHash as createHash7}from"node:crypto";import*as fs8 from"node:fs";import*as path12 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals9.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals9.spawnSync("git",["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals9.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals9.bunSpawn(["git","-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals9.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve8)=>{timeout=setTimeout(()=>resolve8({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals9.spawnSync("git",["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
188
190
  `)){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=runGit(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
189
191
  `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}async function resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=await runGitAsync(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
190
192
  `)){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(`
@@ -192,7 +194,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
192
194
  `).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:path12.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(path12.resolve(expected.directory)!==path12.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,_internals9;var init_workspace_snapshot=__esm(()=>{init_bun_compat();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals9={spawnSync:child_process.spawnSync,bunSpawn,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve8)=>setImmediate(resolve8)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs8.readFileSync(filePath)}});import*as fs9 from"node:fs";import*as path13 from"node:path";function isExecutableFile(candidate){try{return fs9.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path13.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path13.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path13.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path13.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}function clampTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs))return MAX_RUNNER_TIMEOUT_MS;return Math.min(Math.max(1,Math.floor(timeoutMs)),MAX_RUNNER_TIMEOUT_MS)}function addTimeoutMs(baseMs,deltaMs){if(baseMs>=MAX_TIMEOUT_MS)return MAX_TIMEOUT_MS;return Math.min(MAX_TIMEOUT_MS,baseMs+deltaMs)}function computeSpawnTimeoutMs(timeoutMs){let total=clampTimeoutMs(timeoutMs);for(let windowMs of[TERMINATION_GRACE_MS,TERMINATION_FORCE_MS,TERMINATION_CONFIRM_MS,TREE_TERMINATION_CONFIRM_MS,TERMINATION_FALLBACK_BUFFER_MS])total=addTimeoutMs(total,windowMs);return total}function startBoundedStreamRead(stream,maxBytes,onLimitExceeded){let reader=stream.getReader(),lockReleased=!1,cancelPromise,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancel=async()=>{return cancelPromise??=(async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}})(),cancelPromise};if(maxBytes<=0)return onLimitExceeded?.(),{cancel,promise:(async()=>{return await cancel(),{text:"",truncated:!0}})()};return{promise:(async()=>{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,onLimitExceeded?.(),cancel();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}})(),cancel}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function killProcess(proc){try{proc?.kill(timeoutKillSignal(_internals10.platform()))}catch{}}function requestTermination(proc,signal){try{if(proc?.killTree)return proc.killTree(signal).then(()=>!0,()=>!1);else return proc?.kill(signal),Promise.resolve(proc!==void 0)}catch{return Promise.resolve(!1)}}async function waitForExitWithin(exitPromise,waitMs){if(waitMs<=0)return Promise.resolve(null);let timeoutHandle;try{return await Promise.race([exitPromise,new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>resolve8({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals10.clearTimeout(timeoutHandle)}}async function collectBoundedStreams(stdoutRead,stderrRead,proc,treeAlreadyConfirmed=!1){let reads=Promise.all([stdoutRead.promise,stderrRead.promise]),collected=await waitForValueWithin(reads,STREAM_DRAIN_MS);if(!collected.completed){let treeTermination=waitForValueWithin(requestTermination(proc,"SIGKILL"),TREE_TERMINATION_CONFIRM_MS);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]),collected=await waitForValueWithin(reads,STREAM_CANCEL_MS);let terminationResult=await treeTermination;if(!treeAlreadyConfirmed&&(!terminationResult.completed||!terminationResult.value))return{kind:"unconfirmed-termination"}}if(!collected.completed)return{kind:"cleanup-failed"};return{kind:"collected",stdout:collected.value[0],stderr:collected.value[1]}}async function runExternalTool(options){if(!path13.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,overflowTreeTermination,exitSettled=!1,settledExitCode=null,runnerTimeoutMs=clampTimeoutMs(options.timeoutMs),spawnTimeoutMs=computeSpawnTimeoutMs(runnerTimeoutMs);try{proc=_internals10.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:spawnTimeoutMs,killProcessTree:!0,windowsVerbatimArguments:options.windowsVerbatimArguments});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,exitCode}),exitRacePromise=exitPromise.then((exitCode)=>({kind:"exit",exitCode})),timeout=new Promise((resolve8)=>{timeoutHandle=_internals10.setTimeout(()=>{if(exitSettled){resolve8({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve8({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve8)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve8({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),terminateOnOverflow=()=>{overflowTreeTermination??=requestTermination(proc,"SIGKILL")},stdoutRead=startBoundedStreamRead(proc.stdout,options.maxStdoutBytes,terminateOnOverflow),stderrRead=startBoundedStreamRead(proc.stderr,options.maxStderrBytes,terminateOnOverflow),exitResult=await Promise.race([exitRacePromise,timeout,cancelled]);if(exitResult.kind==="timeout"||exitResult.kind==="cancelled"){let gracefulTreeTermination=requestTermination(proc,"SIGTERM"),confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_GRACE_MS);if(!overflowTreeTermination)overflowTreeTermination=requestTermination(proc,"SIGKILL");let treeTerminationResult=waitForValueWithin(Promise.all([gracefulTreeTermination,overflowTreeTermination]),TREE_TERMINATION_CONFIRM_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_FORCE_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_CONFIRM_MS);let treeTermination=await treeTerminationResult,treeTerminationConfirmed=treeTermination.completed&&treeTermination.value.some(Boolean);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]);let streams2=await collectBoundedStreams(stdoutRead,stderrRead,proc,treeTerminationConfirmed);if(streams2.kind!=="collected")return{status:"spawn-error",exitCode:confirmedExitCode??proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams2.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout:stdout2,stderr:stderr2}=streams2;if(confirmedExitCode===null||!treeTerminationConfirmed)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE};if(exitResult.kind==="timeout")return{status:"timeout",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated};return{status:"cancelled",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:"external tool execution cancelled"}}let streams=await collectBoundedStreams(stdoutRead,stderrRead,proc);if(streams.kind!=="collected")return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout,stderr}=streams;if(overflowTreeTermination){let overflowTermination=await waitForValueWithin(overflowTreeTermination,TREE_TERMINATION_CONFIRM_MS);if(!overflowTermination.completed||!overflowTermination.value)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE}}if(proc.spawnError)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:proc.spawnError.message};if(proc.signalCode)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:`external tool terminated by signal ${proc.signalCode}`};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)_internals10.clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(!exitSettled)killProcess(proc)}}var DEFAULT_WINDOWS_EXTENSIONS,TERMINATION_GRACE_MS=20,TERMINATION_FORCE_MS=20,TERMINATION_CONFIRM_MS=20,TREE_TERMINATION_CONFIRM_MS=5100,TERMINATION_FALLBACK_BUFFER_MS=1,STREAM_DRAIN_MS=50,STREAM_CANCEL_MS=50,MAX_TIMEOUT_MS=2147483647,TERMINATION_WINDOWS_MS,MAX_RUNNER_TIMEOUT_MS,UNCONFIRMED_TERMINATION_MESSAGE="external tool process termination could not be confirmed",_internals10;var init_external_tool_runner=__esm(()=>{init_bun_compat();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"],TERMINATION_WINDOWS_MS=TERMINATION_GRACE_MS+TERMINATION_FORCE_MS+TERMINATION_CONFIRM_MS+TREE_TERMINATION_CONFIRM_MS+TERMINATION_FALLBACK_BUFFER_MS,MAX_RUNNER_TIMEOUT_MS=MAX_TIMEOUT_MS-TERMINATION_WINDOWS_MS;_internals10={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs}});import*as fsp2 from"node:fs/promises";import*as path14 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:path14.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(path14.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory,options={}){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals11.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals11.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals11.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(),parsedRaw=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsedRaw)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsedRaw,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let ignoredPaths=new Set((options.ignoredPaths??[]).map((value)=>value.replace(/\\/g,"/"))),keepPath=(value)=>!ignoredPaths.has(value.replace(/\\/g,"/")),parsed={...parsedRaw,dirtyTrackedPaths:parsedRaw.dirtyTrackedPaths.filter(keepPath),untrackedPaths:parsedRaw.untrackedPaths.filter(keepPath),unmergedPaths:parsedRaw.unmergedPaths.filter(keepPath),dirtySubmodulePaths:parsedRaw.dirtySubmodulePaths.filter(keepPath)},operations;try{operations=await _internals11.activeOperations(path14.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,_internals11;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"]];_internals11={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 path15 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),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_exports.classifyPrWorkflowGitStateAsync(directory):null;return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let existing=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(existing?.mode===mode){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)existing=await writeStateWhileLocked(directory,{...existing,prFeedbackTargetUrl:options.prUrl,updatedAt:isoNow()})}return options.prHeadSha?bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha):existing}if(existing)throw Error(`BLOCKED: session "${normalizedSessionID}" already has an active ${existing.mode} workflow; complete it before starting ${mode}`);if(options.requireCheckoutPreflight){if(!checkoutPreflight)throw Error("BLOCKED: PR workflow gate state changed during checkout preflight; retry activation against the current project state");let lockedCheckoutPreflight=await _test_exports.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path15.join(".swarm",workflowCheckoutMutationLockRelativePath()),path15.join(".swarm",workflowGateStateLockRelativePath(normalizedSessionID))]});if(lockedCheckoutPreflight.kind==="recovery-required"||lockedCheckoutPreflight.kind==="indeterminate")throw Error(formatCheckoutRecoveryBlock(lockedCheckoutPreflight))}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 writeStateWhileLocked(directory,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 withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID))throw Error("BLOCKED: checkout restoration is allowed only after complete_pr_workflow or abort_pr_workflow clears the active gate");return await assertNoActivePrWorkflowGateForCheckoutRestore(directory),action()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp3.opendir(gateDirectory)}catch(error49){if(error49.code==="ENOENT")return;throw error49}let entriesRead=0,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES)throw Error("BLOCKED: PR workflow gate inventory exceeds the bounded checkout-restoration scan; clear stale workflow state before retrying");if(!/\.json$/i.test(entry.name))continue;if(!entry.isFile())throw Error("BLOCKED: PR workflow gate inventory contains a non-regular state entry; checkout restoration cannot prove project inactivity");let statePath=validateSwarmPath(directory,path15.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath,entry.name);if(!state)continue;let expectedName=path15.basename(workflowGateStateRelativePath(state.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state.sessionID}" has an active ${state.mode} workflow`)}}catch(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}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={kind:"recovery",reason:""}){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().length>0?options.reason.trim().slice(0,500):void 0;if(sanitizedReason===void 0)throw Error(`BLOCKED: ${state.mode} abort requires a non-empty reason (recorded to the audit trail).`);let abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,kind:options.kind,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},...state.checkoutRecovery?{hadTerminalRecovery:!0}:{},openLanes:openLanes.length,reason:sanitizedReason};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify(abortEvent)}
193
195
  `,"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 normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,prHeadSha)))}async function bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,prHeadSha){let normalizedHead=normalizePrHeadSha(prHeadSha),state=await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". 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,checkoutRecovery:void 0,updatedAt:isoNow()};return await _test_exports.beforePrFeedbackTrackingPersist?.(),writeStateWhileLocked(directory,nextState)}async function rebindPrFeedbackHead(directory,sessionID,prHeadSha){let state=await requireBoundState(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");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)throw Error(`BLOCKED: PR_FEEDBACK rebind refused while ${openLanes.length} PR workflow lane(s) are still in flight; collect their results first.`);if(normalizedHead===state.prHeadSha)throw Error(`BLOCKED: PR_FEEDBACK rebind to the current intake head "${normalizedHead}" is a no-op; a rebind must move to a genuinely new verified PR head after merge/rebase repair.`);await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state.sessionID,previousPrHeadSha:state.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}
194
196
  `,"utf-8")}catch{}return withSessionStateMutation(directory,state.sessionID,async()=>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 two separate standalone commands. First run: git -C "${directory}" rev-parse --verify HEAD^0. Then run: git -C "${directory}" cat-file -t HEAD (which must print 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 bare, standalone commands from that directory. If the commit is not present locally, first run \`git fetch origin <pr-head-ref>\`. Then run \`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,"/"),relative5=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative5.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative5}}async function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path15.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=path15.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path15.sep}`)||path15.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=path15.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(`..${path15.sep}`)||path15.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=path15.normalize(path15.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, run `git rev-parse --verify <full_pr_head_sha>^0`, run `git cat-file -t <full_pr_head_sha>` (which must print `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");let commitCount=await _test_exports.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead);if(commitCount===0){if(localHead!==state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires HEAD to equal the immutable intake head (history diverged; resolve it or rebind via rebind_pr_feedback_head)");if(await _test_exports.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readSettledFeedbackClassifications(directory,readyState),inventory=readyState.prFeedbackInventory??[],offenders=inventory.filter((itemId)=>!classifications.has(itemId)||!FEEDBACK_NO_CHANGE_CLASSIFICATIONS.has(classifications.get(itemId)));if(offenders.length>0)throw Error(`BLOCKED: PR_FEEDBACK zero-commit completion requires every inventory item verified as a no-change outcome (DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION); offending items: ${offenders.slice(0,10).join(", ")}. Items with confirmed content changes must follow the exactly-one-reviewed-commit path.`);try{let eventsPath=validateSwarmPath(directory,"events.jsonl");await fsp3.appendFile(eventsPath,`${JSON.stringify({type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}
195
- `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==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(hasUnsafeShellControlSyntax(command))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,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;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 classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted)tokens.push({value:current,quoted,pipeIsDoubleQuoted});current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"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."}}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,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,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,repairKinds,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,repairKinds,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,repairKinds};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,repairKinds};return{covered:!1,evidence:null,issues,salvaged,repairKinds,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.repairKinds.length>0?`structural repairs applied: ${analysis.repairKinds.join(", ")}`:"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])})}function readSettledFeedbackClassifications(directory,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let ref=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===ownership.laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)continue;for(let line of loaded.artifact.text.split(/\r?\n/)){let fields=pipeFields(line);if(fields[0]!=="[FEEDBACK-VERIFIED]"||fields.length!==4||!fields.slice(1,4).every(Boolean)||!FEEDBACK_CLASSIFICATIONS.has(fields[2]))continue;if(!classifications.has(fields[1]))classifications.set(fields[1],fields[2])}}return classifications}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 path15.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((resolve10)=>{timeout=setTimeout(()=>{resolve10({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((resolve10)=>{release=resolve10}),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((resolve10)=>{release=resolve10}),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);return readPrWorkflowGateStateFileFromDisk(filePath,sessionID)}async function readPrWorkflowGateStateFileFromDisk(filePath,stateLabel){let 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 "${stateLabel}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" 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=path15.normalize(path15.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 path15.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path15.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=path15.resolve(directory,".swarm"),parentPath=path15.dirname(path15.resolve(filePath)),relativeParent=path15.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path15.sep}`)||path15.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(path15.sep).filter(Boolean)){let nextPath=path15.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(path15.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=path15.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path15.sep}`)||path15.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(path15.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path15.dirname(filePath))]),relativeFile=path15.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path15.sep}`)||path15.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((resolve10)=>setTimeout(resolve10,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_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,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,FEEDBACK_NO_CHANGE_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};MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS*2+1,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),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).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(),prFeedbackRebindCount:exports_external.number().int().nonnegative().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,_test_exports.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState},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,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,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"]),FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["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,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
197
+ `,"utf-8")}catch{}return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==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(hasUnsafeShellControlSyntax(command))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,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;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 classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted)tokens.push({value:current,quoted,pipeIsDoubleQuoted});current="",quoted=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"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."}}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)}let degradedSourceKeys=new Set;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});for(let degradation of receipt.coverageDegradations)degradedSourceKeys.add(`${degradation.source_batch_id}\x00${degradation.source_lane_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.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha)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){if(degradedSourceKeys.has(`${source.batchId}\x00${source.laneId}`))continue;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,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,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,repairKinds,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,repairKinds,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,repairKinds};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,repairKinds};return{covered:!1,evidence:null,issues,salvaged,repairKinds,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.repairKinds.length>0?`structural repairs applied: ${analysis.repairKinds.join(", ")}`:"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((line)=>pipeFieldsCapped(line,10)).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((line)=>pipeFieldsCapped(line,6)).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((line)=>pipeFieldsCapped(line,4)).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 pipeFieldsCapped(line,expectedFieldCount){let fields=pipeFields(line);if(fields.length<=expectedFieldCount)return fields;let capped=[...fields.slice(0,expectedFieldCount-1),fields.slice(expectedFieldCount-1).join("|")];return warn(`[pr-workflow-gate] verdict row pipe tail-merge applied (expected ${expectedFieldCount} fields, received ${fields.length}); leading machine fields preserved, trailing prose fields merged: ${line.slice(0,120)}`),capped}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((line)=>pipeFieldsCapped(line,4)).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])})}function readSettledFeedbackClassifications(directory,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let ref=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===ownership.laneId)?.result?.outputRef?.trim(),loaded=ref?readLaneOutput(directory,ref):null;if(!loaded)continue;for(let line of loaded.artifact.text.split(/\r?\n/)){let fields=pipeFieldsCapped(line,4);if(fields[0]!=="[FEEDBACK-VERIFIED]"||fields.length!==4||!fields.slice(1,4).every(Boolean)||!FEEDBACK_CLASSIFICATIONS.has(fields[2]))continue;if(!classifications.has(fields[1]))classifications.set(fields[1],fields[2])}}return classifications}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 path15.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((resolve10)=>{timeout=setTimeout(()=>{resolve10({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((resolve10)=>{release=resolve10}),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((resolve10)=>{release=resolve10}),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);return readPrWorkflowGateStateFileFromDisk(filePath,sessionID)}async function readPrWorkflowGateStateFileFromDisk(filePath,stateLabel){let 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 "${stateLabel}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" 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=path15.normalize(path15.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 path15.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowGateStateRelativePath(sessionID){return path15.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=path15.resolve(directory,".swarm"),parentPath=path15.dirname(path15.resolve(filePath)),relativeParent=path15.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path15.sep}`)||path15.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(path15.sep).filter(Boolean)){let nextPath=path15.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(path15.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=path15.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path15.sep}`)||path15.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(path15.resolve(directory,".swarm")),fsp3.realpath(filePath),fsp3.realpath(path15.dirname(filePath))]),relativeFile=path15.relative(realRoot,realFile);if(stat6.isSymbolicLink()||!stat6.isFile()||!sameBigIntFileIdentity(stat6,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path15.sep}`)||path15.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((resolve10)=>setTimeout(resolve10,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_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,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,FEEDBACK_NO_CHANGE_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};MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS*2+1,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),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).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(),prFeedbackRebindCount:exports_external.number().int().nonnegative().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,pipeFieldsCapped,reviewerVerdictRowDigest,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,_test_exports.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState},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,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,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"]),FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["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,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
196
198
 
197
199
  ${USAGE}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
198
200
 
@@ -6463,7 +6465,7 @@ MICRO WORKED EXAMPLE:
6463
6465
  ${CANDIDATE_HEADERS.micro_lane}
6464
6466
  [CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
6465
6467
  Zero findings: ${CLEAN_TEMPLATES.micro_lane}
6466
- ${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals191={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals191.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals191.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals191.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals191.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals191.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals191.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M)")}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals191.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals191.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals191.now()+timeoutMs,hostTimeouts=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals191.now()>=deadline){keepPolling=!1;continue}await _internals191.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals191.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0);if(hostTimeouts.size>0)result.message="Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let collectedRevisionDigest=record3.workspace?.prHeadSha?await _internals191.resolvePrWorkflowRevisionDigestAsync(directory,record3.workspace.prHeadSha)??void 0:void 0,output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length)prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged];if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId,deadline,hostTimeouts){if(typeof session.status!=="function")return!0;try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts);if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals191.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now2-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6468
+ ${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals191={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,now:()=>Date.now(),sleep:sleep3};async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals191.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals191.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>runLane(session,dispatcher,lane,directory,timeoutMs,context))));return buildResult(laneResults,maxConcurrent,timeoutMs)}finally{dispatcher.shutdown()}}async function executeDispatchLanesAsync(args2,directory,context={}){let parsed=DispatchLanesAsyncArgsSchema.safeParse(args2);if(!parsed.success)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:boundZodIssues(parsed.error.issues)});if(typeof parsed.data.mode==="string"){let normalizedMode=parsed.data.mode.trim();parsed.data.mode=normalizedMode.length>0?normalizedMode:void 0}let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return asyncFailureResult({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes_async batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});let requestedBatchId=parsed.data.batch_id??makeBatchId(),session=_internals191.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let common=applyCommonPrompt(parsed.data.lanes,parsed.data.common_prompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId;if(findByBatchId(directory,batchId).length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals191.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals191.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest3)=>digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals191.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let contracted=applyPrWorkflowPromptContract(lanes,{mode:parsed.data.mode,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=applyExplorerFormatSuffix(contracted.lanes,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode});if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});if(lanes=formatted.lanes,context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){if((gateState.prReviewBaseDispatches?.length??0)===0){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error(`BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest})}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation)}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals191.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope})))),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let session=_internals191.getSessionOps();if(!session||typeof session.messages!=="function")return collectFailureResult({failure_class:"no_client",batch_id:parsed.data.batch_id,message:"OpenCode session messages client is not available"});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals191.now()+timeoutMs,hostTimeouts=new Set,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,records=findByBatchId(directory,parsed.data.batch_id,batchFilter);if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){if(await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts),records=findByBatchId(directory,parsed.data.batch_id,batchFilter),allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals191.now()>=deadline){keepPolling=!1;continue}await _internals191.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals191.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0);if(hostTimeouts.size>0)result.message="Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.",result.errors=[...hostTimeouts];return result}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key}=current;if((key==="isRetryable"||key==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key===void 0||CREATE_FAILURE_STATUS_KEYS.has(key)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key))continue;if(key!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts){for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running")continue;if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts)}catch{if(hostTimeouts.size>timeoutCount)continue}}await appendDelegationTransition(directory,record3.correlationId,{status:"cancelled"});continue}if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${record3.laneId??record3.correlationId}"`,hostTimeouts)}catch{continue}if(!messages.data)continue;let transcript=extractAssistantTranscript(messages.data);if(!transcript.text)continue;let collectedRevisionDigest=record3.workspace?.prHeadSha?await _internals191.resolvePrWorkflowRevisionDigestAsync(directory,record3.workspace.prHeadSha)??void 0:void 0,output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,validation2=validatePrReviewDiscoveryLaneCompletion({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0}});if(validation2.ok&&validation2.salvaged?.length)prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged];if(!validation2.ok){terminalStatus="error";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}await appendDelegationTransition(directory,record3.correlationId,{status:terminalStatus,result:prospectiveResult})}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){let promptController=new AbortController,promptResult;try{promptResult=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${args2.timeoutMs}ms`,promptController)}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){await appendDelegationTransition(directory,sessionId,{status:"error",result:{error:message,chars:message.length,truncated:!1,digest:digestText2(message)}}),cleanupAsyncLaunchSession(session,sessionId)}async function isLaneReadyForCollection(session,directory,sessionId,deadline,hostTimeouts){if(typeof session.status!=="function")return!0;try{let status=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts);if(status.error||!status.data)return!1;let current=status.data[sessionId];return current===void 0||current.type==="idle"}catch{return!1}}async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals191.now();for(let record3 of records){if(record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingestion_error")continue;if(now2-record3.updatedAt<=staleTimeoutMs)continue;if(!await isLaneReadyForCollection(session,directory,record3.subagentSessionId,deadline,hostTimeouts))continue;await appendDelegationTransition(directory,record3.correlationId,{status:"stale"})}}function extractAssistantTranscript(messages){let assistantTexts=[];for(let message of messages){if(message.info?.role!=="assistant")continue;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}return{text:assistantTexts.join(`
6467
6469
 
6468
6470
  `),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0;try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let promptResult=await withTimeout2(session.prompt({path:{id:sessionId},body:{agent:lane.agent,tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${timeoutMs}ms`,promptController);if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)});return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){return failedLane(lane,role,startedAt,formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed");return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults}}function recordToLaneResult(record3,batchId){let status=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"||record3.status==="ingesting"?"pending":record3.status,laneId=record3.laneId??record3.correlationId,digest3=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1;if(record3.result?.text!==void 0&&status!=="pending"&&digest3&&outputRef){let key=`${batchId}\x00${laneId}\x00${digest3}`;if(alreadyDelivered=deliveredLaneOutputs.has(key),!alreadyDelivered)deliveredLaneOutputs.add(key),evictDeliveredLaneOutputsIfOverBound()}return{id:laneId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status,session_id:record3.subagentSessionId,generation:record3.generation??1,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{...alreadyDelivered?{output_omitted_repeat:!0}:{output:record3.result.text},output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId,generation){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,generation,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals191.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;return tools.write=!1,tools.edit=!1,tools.patch=!1,tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult2(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes,options={}){let generatedAgentNames=_internals191.getGeneratedAgentNames(),errors5=[],formatted=lanes.map((lane)=>{let role=resolveGeneratedAgentRole(lane.agent,generatedAgentNames),isPrReviewCouncilExplorer=options.mode==="swarm-pr-review:council"&&role.startsWith("council_");if(role!=="explorer"&&!isPrReviewCouncilExplorer)return lane;let rowFamilyIdentity=options.mode==="swarm-pr-review:base"?"For this base explorer lane, use the base row family and put the exact workflow_lane only in the `lane` field.":options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?"For this micro/council lane, use the micro row family and put the exact workflow_lane only in the `micro_lane` field; do not use the base `lane` field.":"Use the row family applicable to this dispatch and put the exact workflow_lane only in that family's `lane` or `micro_lane` field.",exactLane=lane.workflow_lane??lane.id,ownedLanes=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:[exactLane],identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,formatSuffix=options.mode==="swarm-pr-review:base"?BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX:options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX:EXPLORER_CANDIDATE_FORMAT_SUFFIX,controllerIdentity=`CONTROLLER-BOUND OUTPUT IDENTITY: ${identity}. Placeholder text such as "workflow_lane" is invalid. ${rowFamilyIdentity}`,embeddedKnownSuffixes=[EXPLORER_CANDIDATE_FORMAT_SUFFIX,BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX,MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX].filter((suffix)=>lane.prompt.includes(suffix)),expectedSuffixOccurrences=lane.prompt.split(formatSuffix).length-1;if(lane.prompt.endsWith(formatSuffix)&&lane.prompt.includes(controllerIdentity)&&embeddedKnownSuffixes.length===1&&expectedSuffixOccurrences===1)return lane;if(embeddedKnownSuffixes.length>0){let diagnostic=`Lane "${lane.id}" prompt contains an incompatible, duplicate, or controller-unbound explorer output contract for mode "${options.mode??"generic"}"`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let prompt=`${lane.prompt}
6469
6471
 
@@ -6641,8 +6643,8 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
6641
6643
  `).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 _internals226.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 _internals226={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,now2=new Date){let originalQuery=rawQuery,query=rawQuery.trim().replace(/\s+/g," "),currentYear=now2.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 _internals227.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 _internals227={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 path305 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,path305.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 fs186 from"node:fs";import path306 from"node:path";function normalizeVerdict2(verdict){if(!LIVE_VERDICT_SET_2.includes(verdict))throw Error(`Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION', got '${verdict}'`);switch(verdict){case"APPROVED":return"approved";case"NEEDS_REVISION":return"rejected";default:return verdict.toLowerCase()}}function normalizeVerdict4(verdict){if(!LIVE_VERDICT_SET_4.includes(verdict))throw Error(`Invalid verdict: must be 'PASS', 'WARN', 'FAIL', or 'SKIP', got '${verdict}'`);switch(verdict){case"PASS":return"pass";case"WARN":return"warn";case"FAIL":return"fail";case"SKIP":return"skip";default:return verdict.toLowerCase()}}var LIVE_VERDICT_SET_2=["APPROVED","NEEDS_REVISION"],LIVE_VERDICT_SET_4=["PASS","WARN","FAIL","SKIP"],VERDICT_SET_2=LIVE_VERDICT_SET_2,VERDICT_SET_4=LIVE_VERDICT_SET_4;function isAcceptedVerdict2(v){return LIVE_VERDICT_SET_2.includes(v)}function isAcceptedVerdict4(v){return LIVE_VERDICT_SET_4.includes(v)}init_utils2();init_ledger();init_manager();init_utils3();init_logger();init_swarm_artifact_cache();init_create_tool();function buildApprovedPreflightFailure(phase,failure3){return JSON.stringify({success:!1,phase,reason:failure3.reason,message:failure3.message,recovery_guidance:failure3.recovery_guidance},null,2)}async function executeWriteDriftEvidence(args2,directory){let phase=args2.phase;if(!Number.isInteger(phase)||phase<1)return JSON.stringify({success:!1,phase,message:"Invalid phase: must be a positive integer"},null,2);if(!isAcceptedVerdict2(args2.verdict))return JSON.stringify({success:!1,phase,message:"Invalid verdict: must be 'APPROVED' or 'NEEDS_REVISION'"},null,2);let summary=args2.summary;if(typeof summary!=="string"||summary.trim().length===0)return JSON.stringify({success:!1,phase,message:"Invalid summary: must be a non-empty string"},null,2);let normalizedVerdict=_internals228.normalizeVerdict2(args2.verdict),approvedPlan=null,snapshotInfo,qaProfileLocked;if(normalizedVerdict==="approved"){if(approvedPlan=await loadPlanJsonOnly(directory),!approvedPlan)return buildApprovedPreflightFailure(phase,{reason:"plan_required_for_approval",message:"PLAN_REQUIRED_FOR_APPROVAL: plan.json must exist before APPROVED drift evidence can be persisted.",recovery_guidance:"Restore the current .swarm/plan.json and ensure the exact plan identity is available before retrying write_drift_evidence."});let profileLookup=getProfileLookupForIdentity(directory,approvedPlan);if(profileLookup.kind==="missing")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_selection_required",message:"QA_GATE_SELECTION_REQUIRED: no durable QA gate selection exists for this exact plan identity.",recovery_guidance:`Call set_qa_gates with swarm_id=${JSON.stringify(approvedPlan.swarm)} and plan_title=${JSON.stringify(approvedPlan.title)} before retrying write_drift_evidence with the identical identity.`});if(profileLookup.kind==="unbound_legacy")return buildApprovedPreflightFailure(phase,{reason:"qa_gate_identity_unbound",message:"QA_GATE_IDENTITY_UNBOUND: the current plan has a legacy QA gate profile row that is not exact-bound.",recovery_guidance:formatLegacyQaBindingRecovery({swarm:approvedPlan.swarm,title:approvedPlan.title},"retry write_drift_evidence with the identical identity")});try{let lockAnchor=await takeSnapshotEvent(directory,approvedPlan,{source:"drift_approval_prelock"}),planId=derivePlanId(approvedPlan),locked=_internals228.lockProfileForIdentity(directory,approvedPlan,lockAnchor.seq),lockedBySnapshotSeq=locked.locked_by_snapshot_seq??lockAnchor.seq,approvedSnapshot=await takeSnapshotEvent(directory,approvedPlan,{source:"critic_approved",approvalMetadata:{phase,verdict:"APPROVED",summary:summary.trim(),approved_at:new Date().toISOString(),locked_by_snapshot_seq:lockedBySnapshotSeq}});snapshotInfo={seq:approvedSnapshot.seq,timestamp:approvedSnapshot.timestamp,locked_by_snapshot_seq:lockedBySnapshotSeq},qaProfileLocked={plan_id:planId,locked_at:locked.locked_at??"",locked_by_snapshot_seq:locked.locked_by_snapshot_seq??-1}}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return log("[write_drift_evidence] critic-approved persistence failed:",message),buildApprovedPreflightFailure(phase,{reason:"approval_persistence_failed",message:`APPROVAL_PERSISTENCE_FAILED: QA gate profile lock or critic-approved snapshot failed: ${message}`,recovery_guidance:"Resolve the ledger or QA profile persistence failure, then rerun write_drift_evidence. A completed profile lock is idempotent, and no visible approval is published until both persistence steps succeed."})}}let provenance=args2.provenanceAgentName||args2.provenanceSessionId?{agent_name:args2.provenanceAgentName,session_id:args2.provenanceSessionId,captured_at:new Date().toISOString()}:void 0,evidenceContent={entries:[{type:"drift-verification",verdict:normalizedVerdict,summary:summary.trim(),timestamp:new Date().toISOString(),requirementCoverage:args2.requirementCoverage,...provenance?{provenance}:{}}]},filename="drift-verifier.json",relativePath2=path306.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=path306.dirname(validatedPath);try{await fs186.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path306.join(evidenceDir,`.${filename}.tmp`);return await fs186.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs186.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath),JSON.stringify({success:!0,phase,verdict:normalizedVerdict,message:`Drift evidence written to .swarm/evidence/${phase}/drift-verifier.json`,approvedSnapshot:snapshotInfo,qaProfileLocked},null,2)}catch(error93){return JSON.stringify({success:!1,phase,message:error93 instanceof Error?error93.message:String(error93)},null,2)}}var _internals228={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({description:"Write drift verification evidence for a completed phase. Normalizes verdict (APPROVED->approved, NEEDS_REVISION->rejected) and writes a gate-contract formatted EvidenceBundle to .swarm/evidence/{phase}/drift-verifier.json. Use this after critic_drift_verifier delegation to persist the verification result.",args:{phase:exports_external.number().int().min(1).describe("The phase number for the drift verification (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_2).describe("Verdict of the drift verification: 'APPROVED' or 'NEEDS_REVISION'"),summary:exports_external.string().describe("Human-readable summary of the drift verification"),requirementCoverage:exports_external.string().optional().describe("Requirement coverage report from req_coverage tool (JSON string)"),provenanceAgentName:exports_external.string().min(1).optional().describe("Agent name that produced this evidence (optional provenance)"),provenanceSessionId:exports_external.string().min(1).optional().describe("Session ID of the agent that produced this evidence (optional provenance)")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let writeDriftEvidenceArgs={phase:Number(args2.phase),verdict:String(args2.verdict),summary:String(args2.summary??""),requirementCoverage:args2.requirementCoverage!==void 0?String(args2.requirementCoverage):void 0,provenanceAgentName:args2.provenanceAgentName!==void 0?String(args2.provenanceAgentName):void 0,provenanceSessionId:args2.provenanceSessionId!==void 0?String(args2.provenanceSessionId):void 0};return await executeWriteDriftEvidence(writeDriftEvidenceArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_loader();import fs187 from"node:fs";import path307 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=_internals229.validateSwarmPath(directory,path307.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=path307.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,path307.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 fs187.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path307.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs187.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs187.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs187.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,path307.join("evidence","final-council.json")),parsed=JSON.parse(fs187.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals229={validateSwarmPath};init_zod();import fs188 from"node:fs";import path308 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=_internals230.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=path308.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=path308.dirname(validatedPath);try{await fs188.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path308.join(evidenceDir,`.${filename}.tmp`);return await fs188.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs188.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 _internals230={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 fs189 from"node:fs";import path309 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=_internals231.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=path309.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=path309.dirname(validatedPath);try{await fs189.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path309.join(evidenceDir,`.${filename}.tmp`);return await fs189.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs189.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 _internals231={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_candidate_contract();init_pr_workflow_gate();init_utils2();init_create_tool();import{randomUUID as randomUUID29}from"node:crypto";import*as fs190 from"node:fs";import*as path310 from"node:path";var RunIdSchema=exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/,"run_id must be a safe relative identifier"),FindingSchema4=exports_external.object({finding_id:exports_external.string().trim().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),file_line:exports_external.string().trim().min(1).max(1000),evidence:exports_external.string().trim().min(1).max(20000),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"]),severity:exports_external.enum(CANDIDATE_SEVERITIES).optional(),category:exports_external.string().trim().min(1).max(128).optional()}).strict(),HandoffSchema=exports_external.object({pr_url:exports_external.string().url(),finding_ids:exports_external.array(exports_external.string().trim().min(1).max(128)).min(1),summary:exports_external.string().trim().min(1).max(20000),provenance:exports_external.array(exports_external.string().trim().min(1).max(4000)).min(1)}).strict(),WritePrReviewArtifactArgsSchema=exports_external.discriminatedUnion("kind",[exports_external.object({kind:exports_external.literal("findings"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),records:exports_external.array(FindingSchema4).min(1).max(1000)}).strict(),exports_external.object({kind:exports_external.literal("handoff"),run_id:RunIdSchema,pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),handoff:HandoffSchema}).strict()]);function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{let stat20=await fs190.promises.stat(filePath);if(!stat20.isFile()||stat20.size>10485760)throw Error("findings artifact is not a bounded regular file");return(await fs190.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 fs190.promises.mkdir(path310.dirname(filePath),{recursive:!0});let tempPath=path310.join(path310.dirname(filePath),`.${path310.basename(filePath)}.${randomUUID29()}.tmp`);try{await fs190.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs190.promises.rename(tempPath,filePath)}finally{await fs190.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=path310.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(`
6642
6644
  `)+(allRecords.length>0?`
6643
6645
  `:""));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(path310.sep).join("/"),findingIds,handoffRequired),JSON.stringify({success:!0,path:relativeFindingsPath.split(path310.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=path310.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)}
6644
- `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path310.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path310.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 randomUUID30}from"node:crypto";import fs191 from"node:fs";import path311 from"node:path";var _internals232={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals232.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals232.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals232.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=_internals232.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=path311.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(fs191.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=path311.dirname(destination),tempPath=path311.join(parent,`.trigger-eval.${randomUUID30()}.tmp`);try{await fs191.promises.mkdir(parent,{recursive:!0}),await fs191.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6645
- `,{encoding:"utf-8",flag:"wx"}),await fs191.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs191.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,parsed.data.run_id,relativePath2.split(path311.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path311.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,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,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(`
6646
+ `),await markPrReviewHandoffComplete(directory,sessionID,parsed.data.run_id,relativeHandoffPath.split(path310.sep).join("/")),JSON.stringify({success:!0,path:relativeHandoffPath.split(path310.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 randomUUID30}from"node:crypto";import fs191 from"node:fs";import path311 from"node:path";var _internals232={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase};async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals232.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals232.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals232.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,coverageDegradations=[];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.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||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 verifiable micro-lane provenance chain`);let degradationReasons=[];if(record3.status!=="completed")degradationReasons.push(`lane status ${record3.status}`);if(record3.result?.outputDegraded===!0)degradationReasons.push("output degraded");if(record3.result?.transcriptIncomplete===!0)degradationReasons.push("transcript incomplete");if(record3.result?.truncated===!0)degradationReasons.push("output truncated");if((record3.result?.chars??0)<=0)degradationReasons.push("empty output");if(!prReviewDiscoveryArtifactCoversLane(outputArtifact.artifact.text,row.trigger_id,recordOwnedLanes,record3.mode))degradationReasons.push(`no covered candidate or clean row for: ${row.trigger_id}`);for(let reason of degradationReasons)coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason})}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=_internals232.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,coverage_degradations:coverageDegradations}),relativePath2=path311.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(fs191.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=path311.dirname(destination),tempPath=path311.join(parent,`.trigger-eval.${randomUUID30()}.tmp`);try{await fs191.promises.mkdir(parent,{recursive:!0}),await fs191.promises.writeFile(tempPath,`${JSON.stringify(artifact,null,2)}
6647
+ `,{encoding:"utf-8",flag:"wx"}),await fs191.promises.rename(tempPath,destination)}catch(error93){return failure4(`Failed to persist trigger evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}finally{await fs191.promises.rm(tempPath,{force:!0}).catch(()=>{return})}return await markPrReviewTriggerEvaluationComplete(directory,sessionID,parsed.data.run_id,relativePath2.split(path311.sep).join("/")),JSON.stringify({success:!0,path:relativePath2.split(path311.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,coverage_degradation_count:coverageDegradations.length,...coverageDegradations.length>0?{coverage_degradations:coverageDegradations,note:"degraded families recorded on the receipt; disclose them in the final review report"}:{}},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,record_implementation_review:()=>record_implementation_review,record_issue_publication:()=>record_issue_publication,record_issue_reproduction:()=>record_issue_reproduction,record_recurrence_sweep:()=>record_recurrence_sweep,rebind_pr_feedback_head:()=>rebind_pr_feedback_head,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(`
6646
6648
  `);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(`
6647
6649
  `)}
6648
6650
  ${tailContent.join(`