opencode-swarm 7.184.12 → 7.184.13
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.
- package/.opencode/skills/swarm-ci-monitor/SKILL.md +1 -0
- package/.opencode/skills/swarm-pr-feedback/SKILL.md +1 -0
- package/.opencode/skills/swarm-pr-review/SKILL.md +21 -21
- package/.opencode/skills/swarm-pr-review/references/lane-output-recoverability.md +11 -0
- package/.opencode/skills/swarm-pr-review/references/parallel-work-example.md +20 -0
- package/.opencode/skills/swarm-pr-subscribe/SKILL.md +1 -0
- package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
- package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
- package/dist/cli/{auto-checkpoint-7y3x5cv2.js → auto-checkpoint-a2zbyh20.js} +4 -4
- package/dist/cli/{checkpoint-j39f718z.js → checkpoint-s444mhx5.js} +8 -8
- package/dist/cli/{coder-settlement-12ytzqvs.js → coder-settlement-hnwwt3f0.js} +3 -3
- package/dist/cli/{config-doctor-vphp4shw.js → config-doctor-2qhay8ft.js} +2 -2
- package/dist/cli/{core-5a1awn37.js → core-567f7gbz.js} +1 -1
- package/dist/cli/{curator-x2hxjdac.js → curator-antxp3dg.js} +24 -24
- package/dist/cli/{curator-drift-ex0qxt9p.js → curator-drift-ja4d9gq2.js} +5 -5
- package/dist/cli/{curator-llm-factory-ktkat73z.js → curator-llm-factory-0a3svbcn.js} +24 -24
- package/dist/cli/{evidence-summary-service-pfksvp16.js → evidence-summary-service-6ch3b0t5.js} +9 -9
- package/dist/cli/{gate-evidence-8n8kb8tb.js → gate-evidence-zh4fpbnv.js} +2 -2
- package/dist/cli/{guardrail-explain-px94swcz.js → guardrail-explain-pqyp8mx5.js} +25 -25
- package/dist/cli/{guardrail-log-xevw9xht.js → guardrail-log-99zsmp0p.js} +3 -3
- package/dist/cli/{guardrail-reset-18wvqbga.js → guardrail-reset-mzs00j16.js} +24 -24
- package/dist/cli/{hive-promoter-5r35f3ap.js → hive-promoter-f3enyhkn.js} +24 -24
- package/dist/cli/{index-34ysgky0.js → index-09wnx2ke.js} +1 -1
- package/dist/cli/{index-2cbt4b7t.js → index-0p0qwdyy.js} +1 -1
- package/dist/cli/{index-dze05t9h.js → index-258a0p26.js} +4 -4
- package/dist/cli/{index-zzebc1td.js → index-2n1ms79t.js} +1 -1
- package/dist/cli/{index-39ng38sp.js → index-2p3nzm9b.js} +1 -1
- package/dist/cli/{index-5w404j07.js → index-79y6dxa9.js} +1 -1
- package/dist/cli/{index-ryafwy2b.js → index-7vb5rx5w.js} +1 -1
- package/dist/cli/{index-zmtpnyff.js → index-9rm7tw6y.js} +3 -3
- package/dist/cli/{index-cvam011t.js → index-9y5b3nsk.js} +1 -1
- package/dist/cli/{index-rbvndg2d.js → index-a96rm6zk.js} +1 -1
- package/dist/cli/{index-74e43s33.js → index-a9rfvc8j.js} +3 -3
- package/dist/cli/{index-ymhs7hng.js → index-awkb5370.js} +5 -5
- package/dist/cli/{index-fbp7dqfe.js → index-ck2hzp5b.js} +1 -1
- package/dist/cli/{index-azyhws0s.js → index-d2xdwz22.js} +2 -2
- package/dist/cli/{index-vk49btd6.js → index-djct2zsr.js} +1 -1
- package/dist/cli/{index-d42kjvwy.js → index-e593fgq0.js} +2 -2
- package/dist/cli/{index-w33zgxn6.js → index-gz771bj7.js} +1 -1
- package/dist/cli/{index-eqfmabtd.js → index-gzh04gxh.js} +1 -1
- package/dist/cli/{index-5y1qxw0x.js → index-hg1hqfy3.js} +3 -3
- package/dist/cli/{index-n572fdtf.js → index-kxm9wm5e.js} +135 -64
- package/dist/cli/{index-a53f5t61.js → index-nt8g5952.js} +2 -2
- package/dist/cli/{index-53fy0aq2.js → index-pq35rmz5.js} +26 -26
- package/dist/cli/{index-2p1an48j.js → index-ra0z5wza.js} +1 -1
- package/dist/cli/{index-s7rap90y.js → index-sa061g64.js} +3 -3
- package/dist/cli/{index-27wzbb3n.js → index-t7ck2nvk.js} +1 -1
- package/dist/cli/{index-x0jybm74.js → index-tswsm3sw.js} +3 -3
- package/dist/cli/{index-yvmvsej2.js → index-v4ra6hz8.js} +5 -5
- package/dist/cli/{index-kcbkce43.js → index-vd1sd1m5.js} +24 -24
- package/dist/cli/{index-hfs97j0c.js → index-wksedk4d.js} +1 -1
- package/dist/cli/index.js +25 -25
- package/dist/cli/{knowledge-escalator-z5qb6y6s.js → knowledge-escalator-6c813zv8.js} +6 -6
- package/dist/cli/{knowledge-events-gv173j4d.js → knowledge-events-9hbwedqb.js} +4 -4
- package/dist/cli/{knowledge-store-g4sjhep5.js → knowledge-store-8t9wy3ab.js} +1 -1
- package/dist/cli/{knowledge-validator-8whkrsrb.js → knowledge-validator-g61010aw.js} +2 -2
- package/dist/cli/{mcp-x25b3q1g.js → mcp-tyzj9cwy.js} +1 -1
- package/dist/cli/{model-preflight-b21njmda.js → model-preflight-q8pnsjay.js} +24 -24
- package/dist/cli/{pending-delegations-f6rmrqzn.js → pending-delegations-8nah16wj.js} +2 -2
- package/dist/cli/{pr-subscriptions-nmbme4kp.js → pr-subscriptions-rd3gnc3r.js} +1 -1
- package/dist/cli/{pr-workflow-gate-mtzfsmkg.js → pr-workflow-gate-1y8by6bt.js} +32 -24
- package/dist/cli/{scan-cursor-gmpjsr3a.js → scan-cursor-4s30je6f.js} +2 -2
- package/dist/cli/{schema-rvxnxp4n.js → schema-r3v5tb9r.js} +1 -1
- package/dist/cli/{scope-persistence-fqenprq7.js → scope-persistence-vtz91b5n.js} +5 -5
- package/dist/cli/{server-ws1my2dz.js → server-j1ybvgn4.js} +24 -24
- package/dist/cli/{skill-generator-pt1epeer.js → skill-generator-h27wtea0.js} +7 -7
- package/dist/cli/{snapshot-coordination-init-9zrktnh5.js → snapshot-coordination-init-yntqf46w.js} +24 -24
- package/dist/cli/{speckit-checkoff-k13zhgh5.js → speckit-checkoff-qxt03eh3.js} +3 -3
- package/dist/cli/{worktree-collision-ownership-mw3rkc4v.js → worktree-collision-ownership-0a7jtwwe.js} +2 -2
- package/dist/cli/{worktree-isolation-0rtrpf0b.js → worktree-isolation-4re648a3.js} +24 -24
- package/dist/hooks/pr-workflow-gate.d.ts +59 -1
- package/dist/index.js +8 -8
- package/dist/tools/dispatch-lanes.d.ts +7 -0
- package/dist/tools/submit-pr-review-result.d.ts +17 -0
- 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.184.12",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). 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_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
1
|
+
import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.184.13",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction; with task_id, records the high-priority count as todo_scan gate evidence",agents:["architect","researcher","docs","explorer","coder"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},recover_stage_a_task:{description:"recover a task wedged in the settlement-backed Stage A deadlock — workflow at idle/blocked while a COMMITTED accepted coder settlement and green post-settlement pre-check proof justify Stage A: write a settlement-backed stage_a_passed so reviewer/test_engineer can be dispatched, without re-running the coder (issue #2828)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",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; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). 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_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
|
|
2
2
|
|
|
3
3
|
**Speed optimization enabled for this session.**
|
|
4
4
|
|
|
@@ -1302,14 +1302,14 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
|
|
|
1302
1302
|
`,"utf8")}async function renameWithRetry6(from,to){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await hooks.rename(from,to);return}catch(error93){lastError=error93;let code=error93.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")throw error93;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}throw lastError}async function collisionSafeImportedPath(filePath){let canonical=`${filePath}.imported`;if(!await fileExists(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!await fileExists(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path102.basename(filePath)}`)}async function archiveShadowSource(filePath){if(!await fileExists(filePath))return;await renameWithRetry6(filePath,await collisionSafeImportedPath(filePath))}async function syncWorkflowGateShadowProjection(directory,sessionID,state2,options){let filePath=workflowGateStatePath(directory,sessionID);if(options.archiveLegacy&&await fileExists(filePath))await archiveShadowSource(filePath);await writeAtomicJson2(directory,filePath,state2),await writeProjectionMarker(directory,workflowGateStateProjectionMarkerPath(directory,sessionID))}async function repairImportedWorkflowGateShadow(directory,sessionID,state2){let filePath=workflowGateStatePath(directory,sessionID),markerPath=workflowGateStateProjectionMarkerPath(directory,sessionID),live=await readTextFileIfExists(filePath);if(live===null){await syncWorkflowGateShadowProjection(directory,sessionID,state2,{archiveLegacy:!1});return}let canonicalImportedExists=await fileExists(workflowGateStateImportedPath(directory,sessionID)),markerExists=await fileExists(markerPath),projected=serializeWorkflowGateState(state2);if(canonicalImportedExists&&markerExists&&live===projected)return;if(canonicalImportedExists&&live===projected){await writeProjectionMarker(directory,markerPath);return}await syncWorkflowGateShadowProjection(directory,sessionID,state2,{archiveLegacy:!0})}async function removeWorkflowGateShadowProjection(directory,sessionID){for(let filePath of[workflowGateStatePath(directory,sessionID),workflowGateStateProjectionMarkerPath(directory,sessionID)])try{await(hooks.removeShadowProjection??((target)=>fsp5.rm(target,{force:!0})))(filePath)}catch(error93){if(error93.code!=="ENOENT")throw error93}}function appendSessionTerminalizationEvent(directory,sessionID,rowRevision){try{appendCoreEventSync(directory,{type:"pr_workflow_session_terminalized",timestamp:isoNow(),sessionID,rowRevision})}catch{}}async function importLegacyPrWorkflowGateStateIfNeeded(directory,sessionID,allowSalvagedImport=!1){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp5.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}let legacy=allowSalvagedImport?(await(await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate))).readPrWorkflowGateStateForRecovery(directory,sessionID))?.state??null:await readPrWorkflowGateStateFileFromDisk(filePath,sessionID);if(!legacy)return null;let namespace=workflowGateStateCoordinationNamespace(sessionID),outcome=importCoordinationOnce(directory,{source:workflowGateStateRelativePath(sessionID),sourceDigest:createHash48("sha256").update(raw).digest("hex"),rowCount:1,emptyNamespace:namespace},()=>{let result=transitionCoordinationState(directory,{namespace,entityKey:WORKFLOW_STATE_ENTITY_KEY,expectedRevision:null,generation:legacy.revision,status:workflowStateStatus(legacy),payload:JSON.stringify(legacy)});if(result.outcome!=="applied")throw Error(`PR workflow gate state import failed: ${result.outcome}`)}),authoritative=await readPrWorkflowGateStateFromCoordination(directory,sessionID);if(authoritative&&outcome==="imported")await syncWorkflowGateShadowProjection(directory,sessionID,authoritative,{archiveLegacy:!0});return authoritative}async function writeStateWhileLocked(directory,state2,options={}){let bound=requireCodec(),validated=bound.parse(state2),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,validated.sessionID),current=currentAuthoritative?.state??null;if(!current)current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(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=bound.parse({...validated,revision:validated.revision+1});if(transitionCoordinationState(directory,{namespace:workflowGateStateCoordinationNamespace(validated.sessionID),entityKey:WORKFLOW_STATE_ENTITY_KEY,expectedRevision:currentAuthoritative?.rowRevision??null,generation:nextState.revision,status:workflowStateStatus(nextState),payload:JSON.stringify(nextState)}).outcome!=="applied")throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");return await syncWorkflowGateShadowProjection(directory,validated.sessionID,nextState,{archiveLegacy:!1}),rememberState(directory,nextState),nextState}async function deleteStateWhileLocked(directory,sessionID,options={}){let normalizedSessionID=normalizeSessionID(sessionID),currentAuthoritative=null,corruptCoordinationRowRevision;if(options.allowSalvagedRead){let coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")currentAuthoritative={rowRevision:coordination.rowRevision,state:coordination.state};else if(coordination.kind==="corrupt")corruptCoordinationRowRevision=coordination.rowRevision}else currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,normalizedSessionID);let recoveryState=null;if(!currentAuthoritative){if(options.allowSalvagedRead){let{readPrWorkflowGateStateForRecovery}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));recoveryState=(await readPrWorkflowGateStateForRecovery(directory,normalizedSessionID))?.state??null}if(!recoveryState)await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID,{allowSalvagedImport:options.allowSalvagedRead===!0}),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,normalizedSessionID)}let currentRevision=currentAuthoritative?.state.revision??recoveryState?.revision;if(options.expectedStateRevision!==void 0&¤tRevision!==options.expectedStateRevision)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let authoritativeRowRevision=currentAuthoritative?.rowRevision??(recoveryState?corruptCoordinationRowRevision:void 0);if(authoritativeRowRevision!==void 0){if(!deleteCoordinationState(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY,authoritativeRowRevision))throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying")}await removeWorkflowGateShadowProjection(directory,normalizedSessionID),forgetTrackedPrWorkflowState(directory,normalizedSessionID)}async function terminalizePrWorkflowGateForSession(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let row=getCoordinationStateRaw(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY);if(await removeWorkflowGateShadowProjection(directory,normalizedSessionID),await hooks.beforeTerminalizationDelete?.(),row){if(!deleteCoordinationState(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY,row.revision))throw Error("BLOCKED: PR workflow gate state changed concurrently; retry session terminalization");appendSessionTerminalizationEvent(directory,normalizedSessionID,row.revision)}forgetTrackedPrWorkflowState(directory,normalizedSessionID)})}function checkoutMutationProjectKey(directory){return canonicalRootKeyFresh(directory)}async function withCheckoutMutationDeadline(promise3,phase){let timeout;try{return await Promise.race([promise3,new Promise((resolve52)=>{timeout=setTimeout(()=>{resolve52({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},hooks.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key2=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key2)??Promise.resolve(),release,current=new Promise((resolve52)=>{release=resolve52}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key2,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error93){if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2);throw error93}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error93)=>({status:"rejected",error:error93})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}}}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 hooks.openCheckoutLock(lockPath),lock={ownerToken:randomUUID15(),pid:process.pid,createdAtMs:hooks.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 hooks.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error93){writeError=error93}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(error93){if(error93.code!=="EEXIST")throw error93;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(error93){lastError=error93}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}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(hooks.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp5.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp5.rm(lockPath,{force:!0}),!0}catch(error93){if(error93.code==="ENOENT")return!0;throw error93}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}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 hooks.removeCheckoutLock(lockPath),!0}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}}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 hooks.removeCheckoutLock(lockPath);return}catch(error93){if(error93.code==="ENOENT")return;if(lastError=error93,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}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 key2=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key2)??Promise.resolve(),release,current=new Promise((resolve52)=>{release=resolve52}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key2,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key2)===queued)pendingStateMutationsByProjectSession.delete(key2)}}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 fsp5.open(lockPath,"wx"),lock={ownerToken:randomUUID15(),pid:process.pid,createdAtMs:hooks.nowMs()},writeError;try{await hooks.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error93){writeError=error93}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error93){if(error93.code!=="EEXIST")throw error93;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(hooks.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp5.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp5.rm(lockPath,{force:!0}),!0}catch(error93){if(error93.code==="ENOENT")return!0;throw error93}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}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 fsp5.rm(lockPath),!0}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}}var WORKFLOW_GATE_DIR="pr-workflow-gates",WORKFLOW_STATE_COORDINATION_PREFIX="pr-workflow.state",WORKFLOW_STATE_ENTITY_KEY="state",MAX_TRACKED_SESSIONS2=200,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS3=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_COORDINATION_PAYLOAD_CHARS=1048576,trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,defaultPersistenceHooks,hooks,codec3,PrWorkflowCheckoutMutationTimeoutError;var init_persistence=__esm(()=>{init_coordination_store();init_core_events();init_utils2();init_canonical_root();trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map;defaultPersistenceHooks={nowMs:()=>Date.now(),isProcessAlive:defaultIsProcessAlive,openCheckoutLock:(lockPath)=>fsp5.open(lockPath,"wx"),removeCheckoutLock:(lockPath)=>fsp5.rm(lockPath),checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,rename:(from,to)=>fsp5.rename(from,to)},hooks=defaultPersistenceHooks;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"}}});import{createHash as createHash49,randomUUID as randomUUID16}from"node:crypto";import*as fsp6 from"node:fs/promises";import*as path103 from"node:path";function bindPrReviewReentryBindingReader(reader){bindingReader=reader}async function currentBinding(directory,sessionID){if(!bindingReader)throw Error("BLOCKED: re-entry authorization binding reader is not bound (the PR workflow gate must bind it at module init)");return bindingReader(directory,sessionID)}function reentryAuthorizationFilePath(directory,sessionID){let relative26=path103.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`);return validateSwarmPath(directory,relative26)}function reentryAuthorizationImportedPath(directory,sessionID){return`${reentryAuthorizationFilePath(directory,sessionID)}.imported`}function reentryAuthorizationProjectionMarkerPath(directory,sessionID){return`${reentryAuthorizationFilePath(directory,sessionID)}.sqlite-projection`}function reentryAuthorizationCoordinationNamespace(sessionID){return`${AUTHORIZATION_COORDINATION_PREFIX}:${prWorkflowSessionFileStem(sessionID)}`}async function readAuthorizationFile(filePath){let raw;try{let stat12=await fsp6.stat(filePath);if(!stat12.isFile()||stat12.size>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store is not a bounded regular file");raw=await fsp6.readFile(filePath,"utf8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}let decoded=JSON.parse(raw),parsed=AuthorizationFileSchema.safeParse(decoded);if(!parsed.success)throw Error(`reentry authorization store is invalid: ${parsed.error.issues.map((issue3)=>`${issue3.path.join(".")}: ${issue3.message}`).join("; ")}`);return parsed.data}function parseAuthorizationPayload(payload,sessionID){let decoded=JSON.parse(payload),parsed=AuthorizationFileSchema.safeParse(decoded);if(!parsed.success||parsed.data.sessionId!==sessionID)throw Error(`reentry authorization store is invalid for session "${sessionID}"`);return parsed.data}function readAuthorizationsFromCoordination(directory,sessionID){let row=getCoordinationState(directory,reentryAuthorizationCoordinationNamespace(sessionID),AUTHORIZATION_ENTITY_KEY);if(!row)return null;return{rowRevision:row.revision,rowGeneration:row.generation,store:parseAuthorizationPayload(row.payload,sessionID)}}async function renameWithRetryAsync(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=_internals93.renameRetryDelaysMs.length;attempt++)try{await _internals93.renameImpl(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES4.has(code))throw err;if(attempt<_internals93.renameRetryDelaysMs.length)await new Promise((resolve52)=>setTimeout(resolve52,_internals93.renameRetryDelaysMs[attempt]))}throw lastError}async function writeAuthorizationFile(filePath,file3){let serialized2=serializeAuthorizationFile(file3);if(Buffer.byteLength(serialized2,"utf8")>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store exceeds its write bound");await fsp6.mkdir(path103.dirname(filePath),{recursive:!0});let tempPath=path103.join(path103.dirname(filePath),`.${path103.basename(filePath)}.${randomUUID16()}.tmp`);try{await fsp6.writeFile(tempPath,serialized2,{encoding:"utf8",flag:"wx"}),await renameWithRetryAsync(tempPath,filePath)}finally{await fsp6.rm(tempPath,{force:!0}).catch(()=>{return})}}async function fileExists2(filePath){try{return await fsp6.stat(filePath),!0}catch(error93){if(error93.code==="ENOENT")return!1;throw error93}}function serializeAuthorizationFile(file3){return`${JSON.stringify(file3,null,2)}
|
|
1303
1303
|
`}async function readTextFileIfExists2(filePath){try{return await fsp6.readFile(filePath,"utf8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}}async function writeProjectionMarker2(filePath){await fsp6.mkdir(path103.dirname(filePath),{recursive:!0}),await fsp6.writeFile(filePath,`sqlite-projection
|
|
1304
1304
|
`,"utf8")}async function collisionSafeImportedPath2(filePath){let canonical=`${filePath}.imported`;if(!await fileExists2(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!await fileExists2(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path103.basename(filePath)}`)}async function archiveShadowSource2(filePath){if(!await fileExists2(filePath))return;await renameWithRetryAsync(filePath,await collisionSafeImportedPath2(filePath))}async function syncAuthorizationShadowProjection(directory,sessionID,store,options){let filePath=reentryAuthorizationFilePath(directory,sessionID);if(options.archiveLegacy&&await fileExists2(filePath))await archiveShadowSource2(filePath);await writeAuthorizationFile(filePath,store),await writeProjectionMarker2(reentryAuthorizationProjectionMarkerPath(directory,sessionID))}async function repairImportedAuthorizationShadow(directory,sessionID,store){let filePath=reentryAuthorizationFilePath(directory,sessionID),markerPath=reentryAuthorizationProjectionMarkerPath(directory,sessionID),live=await readTextFileIfExists2(filePath);if(live===null){await syncAuthorizationShadowProjection(directory,sessionID,store,{archiveLegacy:!1});return}let canonicalImportedExists=await fileExists2(reentryAuthorizationImportedPath(directory,sessionID)),markerExists=await fileExists2(markerPath),projected=serializeAuthorizationFile(store);if(canonicalImportedExists&&markerExists&&live===projected)return;if(canonicalImportedExists&&live===projected){await writeProjectionMarker2(markerPath);return}await syncAuthorizationShadowProjection(directory,sessionID,store,{archiveLegacy:!0})}async function readAuthorizationsAuthoritative(directory,sessionID){let existing=readAuthorizationsFromCoordination(directory,sessionID);if(existing)return await repairImportedAuthorizationShadow(directory,sessionID,existing.store),existing;let filePath=reentryAuthorizationFilePath(directory,sessionID),raw;try{raw=await fsp6.readFile(filePath,"utf8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}let legacy=await readAuthorizationFile(filePath);if(!legacy)return null;let outcome=importCoordinationOnce(directory,{source:path103.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`),sourceDigest:createHash49("sha256").update(raw).digest("hex"),rowCount:legacy.authorizations.length,emptyNamespace:reentryAuthorizationCoordinationNamespace(sessionID)},()=>{let result=transitionCoordinationState(directory,{namespace:reentryAuthorizationCoordinationNamespace(sessionID),entityKey:AUTHORIZATION_ENTITY_KEY,expectedRevision:null,generation:1,status:"authorizations",payload:JSON.stringify(legacy)});if(result.outcome!=="applied")throw Error(`reentry authorization import failed: ${result.outcome}`)}),imported=readAuthorizationsFromCoordination(directory,sessionID);if(imported&&outcome==="imported")await syncAuthorizationShadowProjection(directory,sessionID,imported.store,{archiveLegacy:!0});return imported}function persistAuthorizationsAuthoritative(directory,sessionID,store,expectedRevision,generation){let result=transitionCoordinationState(directory,{namespace:reentryAuthorizationCoordinationNamespace(sessionID),entityKey:AUTHORIZATION_ENTITY_KEY,expectedRevision,generation,status:"authorizations",payload:JSON.stringify(store)});if(result.outcome!=="applied"&&result.outcome!=="revision_conflict"&&result.outcome!=="stale_generation")throw Error(`reentry authorization persistence failed: ${result.outcome}`);return{outcome:result.outcome}}function pruneAuthorizations(records,nowMs3){let unexpired=records.filter((record3)=>Date.parse(record3.expiresAt)>nowMs3),newest=(left,right)=>{let leftAt=left.consumedAt??left.createdAt,rightAt=right.consumedAt??right.createdAt;return leftAt===rightAt?0:leftAt>rightAt?-1:1},live=unexpired.filter((record3)=>!record3.consumedAt).sort(newest),consumed=unexpired.filter((record3)=>Boolean(record3.consumedAt)).sort(newest);return[...live,...consumed.slice(0,Math.max(0,MAX_PERSISTED_AUTHORIZATIONS-live.length))]}async function issuePrReviewReentryAuthorization(directory,sessionID,request){let trimmedSession=sessionID.trim();if(!trimmedSession)throw Error("BLOCKED: re-entry authorization requires an active sessionID");return withSessionStateMutation(directory,trimmedSession,async()=>{let binding=await currentBinding(directory,trimmedSession);if(!binding||binding.prHeadSha!==request.prHeadSha.toLowerCase())throw Error(`BLOCKED: re-entry authorization requires an active PR_REVIEW workflow bound to the declared head (active: ${binding?.prHeadSha??"(none)"})`);if(request.runId&&binding.runId&&request.runId!==binding.runId)throw Error("BLOCKED: re-entry authorization run does not match the active PR-review run");for(let attempt=0;attempt<MAX_AUTHORIZATION_WRITE_ATTEMPTS;attempt++){let existing=await readAuthorizationsAuthoritative(directory,trimmedSession),nowMs3=Date.now(),now=new Date(nowMs3).toISOString(),records=pruneAuthorizations(existing?.store.authorizations??[],nowMs3);if(records.filter((record4)=>!record4.consumedAt&&record4.role===request.role&&record4.generation===binding.generation).length>0)throw Error(`BLOCKED: an unconsumed re-entry authorization for role "${request.role}" at generation ${binding.generation} already exists; use it (one immediate Task dispatch) before issuing another`);if(records.filter((record4)=>!record4.consumedAt).length>=MAX_ACTIVE_AUTHORIZATIONS)throw Error(`BLOCKED: re-entry authorization store is at its bound of ${MAX_ACTIVE_AUTHORIZATIONS} active authorizations`);let record3={schemaVersion:1,authorizationId:randomUUID16(),sessionId:trimmedSession,...binding.workflowInstanceId?{workflowInstanceId:binding.workflowInstanceId}:{},...binding.runId?{runId:binding.runId}:{},prHeadSha:binding.prHeadSha,revisionDigest:binding.revisionDigest,role:request.role,generation:binding.generation,createdAt:now,expiresAt:new Date(nowMs3+AUTHORIZATION_TTL_MS).toISOString()},nextStore={schemaVersion:1,sessionId:trimmedSession,authorizations:[record3,...records].slice(0,MAX_PERSISTED_AUTHORIZATIONS)};if(persistAuthorizationsAuthoritative(directory,trimmedSession,nextStore,existing?.rowRevision??null,(existing?.rowGeneration??0)+1).outcome!=="applied")continue;return await syncAuthorizationShadowProjection(directory,trimmedSession,nextStore,{archiveLegacy:!1}),record3}throw Error("BLOCKED: re-entry authorization store changed concurrently; reload the active session state before retrying")})}function authorizationMatchesBinding(record3,binding){return binding.prHeadSha===record3.prHeadSha&&binding.revisionDigest===record3.revisionDigest&&binding.generation===record3.generation&&binding.workflowInstanceId===record3.workflowInstanceId&&binding.runId===record3.runId}async function hasPrReviewReentryAuthorizationAgainstBinding(directory,sessionID,request,binding){let trimmedSession=sessionID.trim();if(!trimmedSession)return!1;try{let existing=await readAuthorizationsAuthoritative(directory,trimmedSession);if(!existing)return!1;return pruneAuthorizations(existing.store.authorizations,Date.now()).some((record3)=>!record3.consumedAt&&record3.role===request.role&&record3.sessionId===trimmedSession&&authorizationMatchesBinding(record3,binding))}catch{return!1}}async function reservePrReviewReentryAuthorizationAgainstBinding(directory,sessionID,request,binding){let trimmedSession=sessionID.trim();if(!trimmedSession)return null;try{for(let attempt=0;attempt<MAX_AUTHORIZATION_WRITE_ATTEMPTS;attempt++){let existing=await readAuthorizationsAuthoritative(directory,trimmedSession);if(!existing)return null;let nowMs3=Date.now(),records=pruneAuthorizations(existing.store.authorizations,nowMs3),sameCallIndex=records.findIndex((record3)=>record3.consumedCallId===request.callID&&record3.role===request.role&&record3.sessionId===trimmedSession&&Date.parse(record3.expiresAt)>nowMs3),index=sameCallIndex>=0?sameCallIndex:records.findIndex((record3)=>!record3.consumedAt&&record3.role===request.role&&record3.sessionId===trimmedSession&&Date.parse(record3.expiresAt)>nowMs3);if(index<0){if(records.length!==existing.store.authorizations.length){let prunedStore={...existing.store,authorizations:records};if(persistAuthorizationsAuthoritative(directory,trimmedSession,prunedStore,existing.rowRevision,existing.rowGeneration+1).outcome!=="applied")continue;await syncAuthorizationShadowProjection(directory,trimmedSession,prunedStore,{archiveLegacy:!1})}return null}let candidate=records[index];if(!authorizationMatchesBinding(candidate,binding))return null;if(candidate.consumedCallId===request.callID)return candidate;let consumed={...candidate,consumedAt:new Date(nowMs3).toISOString(),consumedCallId:request.callID};records[index]=consumed;let nextStore={...existing.store,authorizations:records};if(persistAuthorizationsAuthoritative(directory,trimmedSession,nextStore,existing.rowRevision,existing.rowGeneration+1).outcome!=="applied")continue;return await syncAuthorizationShadowProjection(directory,trimmedSession,nextStore,{archiveLegacy:!1}),consumed}return null}catch{return null}}var AUTHORIZATION_TTL_MS=600000,MAX_ACTIVE_AUTHORIZATIONS=8,MAX_PERSISTED_AUTHORIZATIONS=32,REENTRY_AUTHORIZATIONS_MAX_BYTES=65536,AUTHORIZATION_COORDINATION_PREFIX="pr-review.reentry-authorizations",AUTHORIZATION_ENTITY_KEY="authorizations",MAX_AUTHORIZATION_WRITE_ATTEMPTS=5,bindingReader,PrReviewReentryAuthorizationRecordSchema,AuthorizationFileSchema,RENAME_RETRY_DELAYS_MS4,RETRYABLE_RENAME_CODES4,_internals93;var init_authorization=__esm(()=>{init_zod();init_pr_review_contract();init_coordination_store();init_utils2();init_persistence();PrReviewReentryAuthorizationRecordSchema=exports_external.object({schemaVersion:exports_external.literal(1),authorizationId:exports_external.string().min(1).max(64),sessionId:exports_external.string().min(1).max(256),workflowInstanceId:exports_external.string().min(1).max(128).optional(),runId:PrReviewRunIdSchema.optional(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),role:exports_external.enum(["reviewer","test_engineer"]),generation:exports_external.number().int().nonnegative(),createdAt:exports_external.string().datetime(),expiresAt:exports_external.string().datetime(),consumedAt:exports_external.string().datetime().optional(),consumedCallId:exports_external.string().min(1).max(128).optional()}).strict(),AuthorizationFileSchema=exports_external.object({schemaVersion:exports_external.literal(1),sessionId:exports_external.string().min(1).max(256),authorizations:exports_external.array(PrReviewReentryAuthorizationRecordSchema).max(MAX_PERSISTED_AUTHORIZATIONS)}).strict();RENAME_RETRY_DELAYS_MS4=[10,25,50,100,200],RETRYABLE_RENAME_CODES4=new Set(["EPERM","EBUSY","EACCES","EEXIST"]);_internals93={AUTHORIZATION_TTL_MS,MAX_ACTIVE_AUTHORIZATIONS,reentryAuthorizationFilePath,reentryAuthorizationCoordinationNamespace,pruneAuthorizations,authorizationMatchesBinding,hasPrReviewReentryAuthorizationAgainstBinding,renameImpl:(from,to)=>fsp6.rename(from,to),renameRetryDelaysMs:RENAME_RETRY_DELAYS_MS4,renameWithRetryAsync,writeAuthorizationFile}});function zeroOutputResult(result){let outputRef=result.outputRef?.trim(),text=result.text?.trim()??"";return!outputRef&&text.length===0&&(result.chars??0)===0}function classifyPrReviewCircuitSignal(record3){if(!CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record3.status))return null;let result=record3.terminalResult?.result??record3.result,providerClass=result?.terminalErrorClass?.category;if(result?.terminalErrorClass&&providerClass){if(record3.status!=="error")return{kind:"ignored",reason:"cancellation"};if(result.terminalErrorClass.kind==="provider")return{kind:"provider_terminal",providerClass,batchId:record3.batchId??"",laneId:record3.laneId??"",terminalAtMs:record3.terminalResult?.recordedAt??record3.completedAt??record3.updatedAt??record3.createdAt??0};if(result.terminalErrorClass.kind==="aborted")return{kind:"ignored",reason:"cancellation"};if(result.terminalErrorClass.kind==="output_length")return{kind:"ignored",reason:"validation"};return{kind:"ignored",reason:"unknown"}}if(result?.workflowLaneFailureClass==="liveness")return{kind:"ignored",reason:"host_abandonment"};switch(record3.status){case"error":return{kind:"ignored",reason:"unknown"};case"stale":return{kind:"ignored",reason:"stale_observation"};case"cancelled":return{kind:"ignored",reason:"cancellation"};case"completed":return zeroOutputResult(result??{})?{kind:"ignored",reason:"parser"}:null;default:return null}}function scanPrReviewCircuitEvidence(signals,generation,waterlineMs){let byKey=new Map;for(let signal of signals){if(signal.kind!=="provider_terminal")continue;if(signal.terminalAtMs<=0||waterlineMs!==void 0&&signal.terminalAtMs<=waterlineMs)continue;let key2=`${generation}\x00${signal.batchId}\x00${signal.laneId}`,existing=byKey.get(key2);if(!existing||existing.signal.terminalAtMs<signal.terminalAtMs)byKey.set(key2,{signal})}let grouped=new Map,ordered=[...byKey.values()].sort((left,right)=>right.signal.terminalAtMs-left.signal.terminalAtMs||left.signal.providerClass.localeCompare(right.signal.providerClass)||left.signal.batchId.localeCompare(right.signal.batchId)||left.signal.laneId.localeCompare(right.signal.laneId));for(let{signal}of ordered){let list=grouped.get(signal.providerClass)??[];if(list.length<PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT)list.push(signal);grouped.set(signal.providerClass,list)}return grouped}function adoptPrReviewCircuit(raw,nowMs3){if(raw===void 0||raw===null)return{kind:"absent"};let asV2=PrReviewCircuitRecordV2Schema.safeParse(raw);if(asV2.success)return{kind:"v2",record:asV2.data};let asLegacy=PrReviewCircuitLegacyRecordSchema.safeParse(raw);if(asLegacy.success)return{kind:"migrated",record:freshRecord(nowMs3,!0),diagnostic:{code:"migrated_legacy_circuit",legacySignatureCount:asLegacy.data.contributors.length}};let body=JSON.stringify(raw),hash4="";try{let h=2166136261;for(let index=0;index<body.length;index+=1)h^=body.charCodeAt(index),h=Math.imul(h,16777619);hash4=(h>>>0).toString(16).padStart(8,"0")}catch{hash4="unserializable"}return{kind:"malformed",diagnostic:{code:"malformed_circuit_dropped",bodyHash8:hash4,byteLength:body.length}}}function freshRecord(nowMs3,withWaterline){return{version:2,state:"CLOSED",generation:1,contributors:[],...withWaterline?{evidenceWaterline:new Date(nowMs3).toISOString()}:{}}}function advancePrReviewCircuit(current,input){let record3=current??freshRecord(input.nowMs,!1);if(record3.state==="CLOSED"){let evidence2=scanPrReviewCircuitEvidence(input.laneSignals,record3.generation,record3.evidenceWaterline?Date.parse(record3.evidenceWaterline):void 0),best=null;for(let[providerClass,lanes]of evidence2){if(lanes.length<input.threshold)continue;if(!best||lanes.length>best.lanes.length||lanes.length===best.lanes.length&&providerClass.localeCompare(best.providerClass)<0)best={providerClass,lanes}}if(!best)return{action:"admit",changed:!1};let openedAt=new Date(input.nowMs).toISOString();return{action:"block",reason:"circuit_open",changed:!0,record:{...record3,state:"OPEN",providerClass:best.providerClass,contributors:best.lanes.map((signal2)=>({batchId:signal2.batchId,laneId:signal2.laneId,terminalAt:new Date(signal2.terminalAtMs).toISOString()})),openedAt,openUntil:new Date(input.nowMs+input.openDurationMs).toISOString()}}}if(record3.state==="OPEN"){let openUntilMs=record3.openUntil?Date.parse(record3.openUntil):0;if(input.nowMs<openUntilMs)return{action:"block",reason:"circuit_open",changed:!1};if(!input.admission)return{action:"block",reason:"circuit_open",changed:!1};return{action:"admit_as_probe",changed:!0,record:{...record3,state:"HALF_OPEN",probe:{batchId:input.admission.batchId,laneId:input.admission.laneId,admittedAt:new Date(input.nowMs).toISOString()}}}}let probe2=record3.probe;if(!probe2)return{action:"block",reason:"probe_in_flight",changed:!1};if(input.admission&&input.admission.batchId===probe2.batchId&&!input.probeObservation)return{action:"admit_as_probe",changed:!1};if(!input.probeObservation)return{action:"block",reason:"probe_in_flight",changed:!1};let{terminalStatus,signal}=input.probeObservation;if(signal?.kind==="provider_terminal"){let contributor={batchId:probe2.batchId,laneId:probe2.laneId,terminalAt:new Date(signal.terminalAtMs).toISOString()},contributors=[...record3.contributors.filter((entry)=>!(entry.batchId===contributor.batchId&&entry.laneId===contributor.laneId)),contributor].slice(-PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT);return{action:"block",reason:"circuit_open",changed:!0,record:{...record3,state:"OPEN",contributors,openUntil:new Date(input.nowMs+input.openDurationMs).toISOString(),probe:void 0}}}if(terminalStatus==="completed"&&signal===null)return{action:"admit",changed:!0,record:{version:2,state:"CLOSED",generation:record3.generation+1,contributors:[],evidenceWaterline:new Date(input.probeObservation.terminalAtMs||input.nowMs).toISOString()}};return{action:"block",reason:"circuit_open",changed:!0,record:{...record3,state:"OPEN",openUntil:new Date(input.nowMs+input.openDurationMs).toISOString(),probe:void 0}}}function resolvePrReviewResiliencePolicy(policy){let defaults=DEFAULT_PR_REVIEW_RESILIENCE_CONFIG;return{enabled:policy?.enabled??defaults.enabled,canaryProbeMs:policy?.canary_probe_ms??defaults.canary_probe_ms,statusProbeTimeoutMs:policy?.status_probe_timeout_ms??defaults.status_probe_timeout_ms,correlatedFailureThreshold:policy?.correlated_failure_threshold??defaults.correlated_failure_threshold,maxRetryAttemptsAfterInitial:policy?.max_retry_attempts_after_initial??defaults.max_retry_attempts_after_initial,circuitOpenDurationMs:policy?.circuit_open_duration_ms??defaults.circuit_open_duration_ms}}function resetPrReviewResilienceForReEnable(args2){let previousGeneration=args2.previousCircuit&&"version"in args2.previousCircuit?args2.previousCircuit.generation:1;return{...freshRecord(args2.nowMs,!0),generation:previousGeneration+1}}function rollbackPrReviewCircuitProbe(circuit,nowMs3,openDurationMs){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return circuit;return{...circuit,state:"OPEN",openUntil:new Date(nowMs3+openDurationMs).toISOString(),probe:void 0}}var PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT=768,PrReviewCircuitLegacyRecordSchema,PrReviewCircuitRecordV2Schema,PrReviewCircuitRecordSchema,CIRCUIT_TERMINAL_DELEGATION_STATUSES;var init_circuit=__esm(()=>{init_zod();init_schema();PrReviewCircuitLegacyRecordSchema=exports_external.object({signature:exports_external.string().min(1).max(512),count:exports_external.number().int().min(2).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict()).min(2).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),openedAt:exports_external.string().min(1)}).strict(),PrReviewCircuitRecordV2Schema=exports_external.object({version:exports_external.literal(2),state:exports_external.enum(["CLOSED","OPEN","HALF_OPEN"]),generation:exports_external.number().int().min(1),providerClass:exports_external.string().min(1).max(128).optional(),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),terminalAt:exports_external.string().min(1)}).strict()).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),openedAt:exports_external.string().min(1).optional(),openUntil:exports_external.string().min(1).optional(),evidenceWaterline:exports_external.string().min(1).optional(),probe:exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),admittedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrReviewCircuitRecordSchema=exports_external.union([PrReviewCircuitLegacyRecordSchema,PrReviewCircuitRecordV2Schema]),CIRCUIT_TERMINAL_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"])});import{createHash as createHash50}from"node:crypto";import*as fs67 from"node:fs/promises";import*as path104 from"node:path";function parseCandidateConfidence(value){if(typeof value!=="string")throw Error("Invalid candidate confidence: expected LOW, MEDIUM, or HIGH");let normalized=value.trim().toUpperCase();if(normalized!=="LOW"&&normalized!=="MEDIUM"&&normalized!=="HIGH")throw Error(`Invalid candidate confidence "${value}": expected LOW, MEDIUM, or HIGH`);return{label:normalized,score:CONFIDENCE_SCORE[normalized]}}function tokens(value){return new Set(value.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter((token)=>token.length>=3&&!TOKEN_STOPWORDS.has(token)).map((token)=>TOKEN_ALIASES[token]??token))}function semanticSimilaritySets(a,b){if(a.size===0||b.size===0)return 0;let intersection3=0;for(let token of a)if(b.has(token))intersection3+=1;return intersection3/(a.size+b.size-intersection3)}function normalizedLocation(location){let file3=location.file.replaceAll("\\","/").trim().toLocaleLowerCase("en-US"),line=Number(location.line),lineEnd=location.lineEnd===void 0?line:Number(location.lineEnd);return`${file3}:${line}-${lineEnd}`}function normalizedCategory(category){return category.trim().toLocaleLowerCase("en-US")}function severity(value){if(value==="CRITICAL"||value==="HIGH"||value==="MEDIUM"||value==="LOW"||value==="INFO"||value==="NONE")return value;throw Error(`Invalid finding severity "${String(value)}"`)}function action(value){if(value==="route_to_reviewer"||value==="route_to_critic"||value==="report"||value==="suppress_with_reason"||value==="handoff_to_feedback")return value;return"report"}function status(value){if(value==="UNRESOLVED"||value==="CONFIRMED"||value==="DISPROVED"||value==="NON_ACTIONABLE"||value==="PRE_EXISTING")return value;return"UNRESOLVED"}function provenanceKey(value){return value.identity.trim()}function uniqueProvenance(values){let unique2=new Map;for(let value of values){if(typeof value.identity!=="string"||!value.identity.trim())throw Error("Finding provenance identity must be non-empty");let key2=provenanceKey(value);if(!unique2.has(key2))unique2.set(key2,{...value})}return[...unique2.values()].sort((a,b)=>provenanceKey(a).localeCompare(provenanceKey(b)))}function sameFinding(left,leftTokens,right,rightTokens){if(normalizedCategory(left.category)!==normalizedCategory(right.category))return!1;if(normalizedLocation(left.location)!==normalizedLocation(right.location))return!1;if(left.finding.trim()===right.finding.trim())return!0;return semanticSimilaritySets(leftTokens,rightTokens)>=0.3}function findingId(value){let material=`${normalizedLocation(value.location)}|${normalizedCategory(value.category)}|${[...tokens(value.finding)].sort().join(",")}`,hash4=2166136261;for(let char of material)hash4^=char.charCodeAt(0),hash4=Math.imul(hash4,16777619);return`finding-${(hash4>>>0).toString(16).padStart(8,"0")}`}function lowestConfidence(values){return values.reduce((lowest,value)=>CONFIDENCE_RANK[value]<CONFIDENCE_RANK[lowest]?value:lowest)}function synthesizePrReviewFindings(input){if(input.candidates.length>MAX_FINDING_SYNTHESIS_CANDIDATES)throw Error(`Finding synthesis accepts at most ${MAX_FINDING_SYNTHESIS_CANDIDATES} candidates`);let groups=[],groupTokens=[],diagnostics=[];for(let raw of input.candidates){if(!raw||typeof raw!=="object")throw Error("Finding candidate must be an object");let candidate={...raw,finding:typeof raw.finding==="string"?raw.finding.trim():"",severity:severity(raw.severity),confidence:parseCandidateConfidence(raw.confidence).label,category:typeof raw.category==="string"?raw.category.trim():""};if(!candidate.finding||!candidate.category||!candidate.location?.file)throw Error("Finding candidate requires non-empty finding, category, and location");let candidateTokens=tokens(candidate.finding),existingIndex=-1;for(let index=0;index<groups.length;index++)if(sameFinding(groups[index][0],groupTokens[index],candidate,candidateTokens)){existingIndex=index;break}if(existingIndex>=0)groups[existingIndex].push(candidate);else groups.push([candidate]),groupTokens.push(candidateTokens)}let findings=groups.map((group)=>{let first=group[0],provenance=uniqueProvenance(group.flatMap((candidate)=>Array.isArray(candidate.provenance)?candidate.provenance:[candidate.provenance])),severities=group.map((candidate)=>severity(candidate.severity)),confidenceValues=group.map((candidate)=>parseCandidateConfidence(candidate.confidence).label),finalSeverity=severities.reduce((highest,value)=>SEVERITY_RANK[value]>SEVERITY_RANK[highest]?value:highest),confidence=provenance.length>=2?"HIGH":lowestConfidence(confidenceValues);if(new Set(severities).size>1||new Set(confidenceValues).size>1)diagnostics.push(`conservative disagreement at ${normalizedLocation(first.location)}`);let finalAction=group.map((candidate)=>action(candidate.action)).reduce((mostRestrictive,value)=>ACTION_RANK[value]>ACTION_RANK[mostRestrictive]?value:mostRestrictive),finalStatus=group.map((candidate)=>status(candidate.status)).reduce((mostConservative,value)=>STATUS_RANK[value]>STATUS_RANK[mostConservative]?value:mostConservative),sourceFindingIds=[...new Set(group.flatMap((candidate)=>typeof candidate.sourceFindingId==="string"?[candidate.sourceFindingId]:[]))].sort();return{id:findingId(first),finding:first.finding,severity:finalSeverity,action:finalAction,confidence,confidenceScore:CONFIDENCE_SCORE[confidence],agreementCount:provenance.length,category:first.category,location:{...first.location},provenance,status:finalStatus,sourceFindingIds}});return{policyVersion:FINDING_POLICY_VERSION,findings,diagnostics}}function evaluateFinalFindingPolicy(input){if(input.policyVersion!==FINDING_POLICY_VERSION)throw Error(`Unsupported finding policy version ${input.policyVersion}`);let invalidProvenance=input.coverage.provenance==="invalid",noCoverage=input.coverage.quality==="none"||input.coverage.kind==="base"&&input.coverage.quality==="partial"&&input.findings.length===0,coverageDisposition=invalidProvenance?"INVALID_PROVENANCE":noCoverage?"NO_COVERAGE":input.coverage.quality==="degraded"&&input.coverage.disclosed?"DEGRADED_DISCLOSED":input.coverage.quality==="complete"?"COMPLETE":"PARTIAL";if(input.finalStatus!=="COMPLETE"||invalidProvenance||noCoverage)return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["INCOMPLETE"],coverageDisposition,blockingFindingIds:[]};let blockingFindingIds=[];for(let[index,value]of input.findings.entries()){let currentSeverity=severity(value.severity),currentStatus=String(value.status).toUpperCase(),currentAction=action(value.action);if(!(currentStatus==="UNRESOLVED"||currentStatus==="UNVERIFIED"||currentStatus==="CONFIRMED")||currentSeverity==="NONE")continue;if(currentSeverity==="CRITICAL"||currentSeverity==="HIGH"||currentSeverity==="MEDIUM"&¤tAction!=="report")blockingFindingIds.push(String(value.id??index))}if(blockingFindingIds.length>0)return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds};if(coverageDisposition==="DEGRADED_DISCLOSED"||coverageDisposition==="PARTIAL")return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds};return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["APPROVE","REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds}}function settleCriticFinding(input){if(input.outcome==="NEEDS_MORE_EVIDENCE")return{terminal:!1,status:input.outcome,finalFinding:{...input.finding},handoffFindingIds:[]};if(input.outcome==="DISPROVED")return{terminal:!0,status:input.outcome,finalFinding:{...input.finding,status:"DISPROVED",severity:"NONE",action:"suppress_with_reason"},handoffFindingIds:[]};if(input.outcome==="DOWNGRADED"&&input.finalSeverity===void 0)throw Error("DOWNGRADED critic finding requires an explicit final severity");let finalSeverity=severity(input.finalSeverity??input.finding.severity);if(input.outcome==="UPHELD"&&finalSeverity==="NONE")throw Error("UPHELD critic finding cannot have NONE severity");if(input.outcome==="DOWNGRADED"&&finalSeverity==="CRITICAL")throw Error("DOWNGRADED critic finding cannot remain CRITICAL");let finalAction=action(input.finalAction??input.finding.action);return{terminal:!0,status:input.outcome,finalFinding:{...input.finding,severity:finalSeverity,action:finalAction},handoffFindingIds:finalAction==="handoff_to_feedback"&&input.finding.status!=="DISPROVED"?[input.finding.id]:[]}}function deriveFeedbackHandoffFindingIds(records){return[...new Set(records.filter((record3)=>record3.status==="CONFIRMED"&&record3.next_action==="handoff_to_feedback").map((record3)=>record3.finding_id))].sort()}function assessTerminalReadiness(input){let blockers=[];if(!input.baseReceipt?.valid)blockers.push("BASE_RECEIPT_MISSING");if(input.reviewerReceipts.length===0||input.reviewerReceipts.some((receipt)=>!receipt.valid))blockers.push("REVIEWER_RECEIPT_MISSING");if(!input.criticReceipt?.valid)blockers.push("CRITIC_RECEIPT_MISSING");if(input.criticReceipt?.valid&&input.criticSettlements&&input.criticSettlements.length===0)blockers.push("CRITIC_SETTLEMENT_MISSING");if(input.council.enabled&&!input.council.receipt?.valid)blockers.push("COUNCIL_RECEIPT_MISSING");if(input.coverage.kind==="micro"&&input.coverage.provenance==="invalid")blockers.push("MICRO_PROVENANCE_INVALID");if(input.coverage.quality==="degraded"&&!input.coverage.disclosed)blockers.push("MICRO_DEGRADATION_UNDISCLOSED");if(input.criticSettlements?.some((settlement)=>!settlement.terminal))blockers.push("CRITIC_SETTLEMENT_INCOMPLETE");return{ready:blockers.length===0,blockers,degradedCoverageDisclosed:input.coverage.quality==="degraded"&&input.coverage.provenance==="valid"&&input.coverage.disclosed===!0}}function reviewOutcomeSynthesisDigest(synthesis){return createHash50("sha256").update(JSON.stringify(synthesis),"utf8").digest("hex")}function safeTaskId(taskId){let value=taskId.trim();if(!/^[A-Za-z0-9_.-]{1,128}$/.test(value))throw Error("Review outcome taskId must be a bounded path-safe identifier");return value}async function persistReviewOutcome(input){let sessionId=input.routeReceipt.sessionId.trim(),taskId=safeTaskId(input.routeReceipt.taskId);if(!sessionId)throw Error("Review outcome sessionId must be non-empty");let relativeEvidence=path104.join("pr-review",taskId,"finding-policy.json"),evidencePath=validateSwarmPath(input.projectRoot,relativeEvidence),eventsPath=coreEventsFilePath(input.projectRoot),evidence2={schemaVersion:FINDING_POLICY_VERSION,sessionId,taskId,routeReceipt:input.routeReceipt,synthesis:input.synthesis,synthesisDigest:reviewOutcomeSynthesisDigest(input.synthesis),persistedAt:new Date().toISOString()};await ensurePrWorkflowSafeParentDirectory(input.projectRoot,evidencePath);let alreadyPersisted=!1;try{let existing=JSON.parse(await fs67.readFile(evidencePath,"utf8"));if(!(existing.schemaVersion===FINDING_POLICY_VERSION&&existing.sessionId===sessionId&&existing.taskId===taskId&&JSON.stringify(existing.routeReceipt)===JSON.stringify(input.routeReceipt)&&JSON.stringify(existing.synthesis)===JSON.stringify(input.synthesis)&&existing.synthesisDigest===reviewOutcomeSynthesisDigest(input.synthesis)))throw Error("Review outcome already exists with conflicting route or synthesis data");alreadyPersisted=!0}catch(error93){if(error93.code!=="ENOENT")throw error93}if(!alreadyPersisted)await writeAtomicJson2(input.projectRoot,evidencePath,evidence2);let reviewEvents=readReviewEvents(input.projectRoot,sessionId,taskId),{events}=reviewEvents,auditWindowComplete=reviewEvents.coverage!=="truncated"&&!reviewEvents.truncated,shouldEnsureAuditEvents=!alreadyPersisted||auditWindowComplete;if(shouldEnsureAuditEvents&&!events.some((event)=>event.type==="review.route.receipt"))appendCoreEventSync(input.projectRoot,{type:"review.route.receipt",sessionId,taskId,receiptVersion:input.routeReceipt.version});if(shouldEnsureAuditEvents&&!events.some((event)=>event.type==="review.finding.synthesis"))appendCoreEventSync(input.projectRoot,{type:"review.finding.synthesis",sessionId,taskId,policyVersion:FINDING_POLICY_VERSION,findingCount:Array.isArray(input.synthesis.findings)?input.synthesis.findings.length:0});return{persisted:!0,evidencePath,eventsPath}}async function readReviewOutcome(input){let taskId=safeTaskId(input.taskId),evidencePath=validateSwarmPath(input.projectRoot,path104.join("pr-review",taskId,"finding-policy.json")),evidence2=JSON.parse(await fs67.readFile(evidencePath,"utf8"));if(evidence2.sessionId!==input.sessionId||evidence2.taskId!==taskId||evidence2.schemaVersion!==FINDING_POLICY_VERSION)throw Error("Review outcome evidence identity or schema mismatch");if(!evidence2.synthesis||evidence2.synthesisDigest!==reviewOutcomeSynthesisDigest(evidence2.synthesis))throw Error("Review outcome evidence synthesis integrity mismatch");let reviewEvents=readReviewEvents(input.projectRoot,input.sessionId,taskId),{events}=reviewEvents;if(reviewEvents.coverage!=="truncated"&&!reviewEvents.truncated&&(!events.some((event)=>event.type==="review.route.receipt")||!events.some((event)=>event.type==="review.finding.synthesis")))throw Error("Review outcome evidence audit events are incomplete");return{evidence:evidence2,events,auditCoverage:reviewEvents.coverage}}function readReviewEvents(projectRoot,sessionId,taskId){let read=readCoreEvents(projectRoot);return{events:read.text.split(`
|
|
1305
|
-
`).flatMap((line)=>{try{let event=JSON.parse(line);return event.sessionId===sessionId&&event.taskId===taskId?[event]:[]}catch{return[]}}),coverage:read.coverage,truncated:read.truncated}}var FINDING_POLICY_VERSION=1,CONFIDENCE_SCORE,CONFIDENCE_RANK,SEVERITY_RANK,TOKEN_ALIASES,TOKEN_STOPWORDS,MAX_FINDING_SYNTHESIS_CANDIDATES=256,ACTION_RANK,STATUS_RANK;var init_finding_policy=__esm(()=>{init_core_events();init_utils2();init_persistence();CONFIDENCE_SCORE={LOW:0.35,MEDIUM:0.65,HIGH:0.95},CONFIDENCE_RANK={LOW:0,MEDIUM:1,HIGH:2},SEVERITY_RANK={NONE:0,INFO:1,LOW:2,MEDIUM:3,HIGH:4,CRITICAL:5};TOKEN_ALIASES={authorization:"auth",authorized:"auth",authorise:"auth",authorised:"auth",permissions:"permission",checking:"check",checked:"check",checks:"check",reading:"read",reads:"read",requests:"request",path:"endpoint",skips:"skip",skipped:"skip",skipping:"skip"},TOKEN_STOPWORDS=new Set(["the","and","for","with","from","evidence","critic","reviewer","explorer","rationale","reason","change","probe"]);ACTION_RANK={suppress_with_reason:0,report:1,handoff_to_feedback:2,route_to_reviewer:3,route_to_critic:4},STATUS_RANK={DISPROVED:0,PRE_EXISTING:1,NON_ACTIONABLE:1,UNRESOLVED:2,CONFIRMED:3}});import{createHash as createHash51}from"node:crypto";import{readFileSync as readFileSync41}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path105 from"node:path";function bindPrReviewCompletionHelpers(helpers){gateHelpers=helpers}function requireBoundHelpers(){if(!gateHelpers)throw Error("BLOCKED: completion settlement helpers are not bound (the PR workflow gate must bind them at module init)");return gateHelpers}function createPrReviewGateContext(directory,state2){return requireBoundHelpers().createPrReviewGateContext(directory,state2)}function requireBoundState(directory,sessionID,expectedMode){return requireBoundHelpers().requireBoundState(directory,sessionID,expectedMode)}function readPrWorkflowGateStateFromDisk2(directory,sessionID){return requireBoundHelpers().readPrWorkflowGateStateFromDisk(directory,sessionID)}function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){return requireBoundHelpers().readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label)}function successfulObligationsFromExactBatch(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics){return requireBoundHelpers().successfulObligationsFromExactBatch(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics)}function recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers().recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function validatePrReviewDiscoveryLaneCompletion(input){return requireBoundHelpers().validatePrReviewDiscoveryLaneCompletion(input)}function validateExactStructuredReceiptCoverage(input){return requireBoundHelpers().validateExactStructuredReceiptCoverage(input)}function allowedPrReviewReportVerdicts(kind,findings=[]){if(kind==="PARTIAL"&&findings.length===0)return["REQUEST_CHANGES","INCOMPLETE"];let supported=evaluateFinalFindingPolicy({policyVersion:1,finalStatus:"COMPLETE",coverage:kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings:[...findings]}).permittedVerdicts.filter((value)=>(value==="APPROVE"||value==="REQUEST_CHANGES"||value==="INCOMPLETE")&&(kind==="COMPLETE"||value!=="APPROVE"));return supported.length>0?supported:["INCOMPLETE"]}function normalizePrReviewPartialBaseCoverageRecord(record3){if("missingDimension"in record3)return{schemaVersion:2,runId:record3.runId,prHeadSha:record3.prHeadSha,revisionDigest:record3.revisionDigest,unresolvedDimensions:[{dimension:record3.missingDimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:record3.failureClass,terminalEventId:record3.terminalEventId,safeDetail:PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[record3.failureClass]}],admittedAt:record3.admittedAt};return record3}function summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest){let successful2=new Set,inFlight=new Set,contractFailed=new Set,contractRetried=new Set(state2.prReviewContractRetryDimensions??[]),dedicatedSuccessful=new Set,terminallyFailed=new Set,delegationReadUncertain;for(let batch of state2.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful2.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 semanticallyValidLaneIds=new Set(recordsPassingBatchIntegrity(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified,state2)).map((qualified)=>qualified.record.laneId)),recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain"){delegationReadUncertain=`delegation store unreadable after ${recordsRead.attempts} attempts (${recordsRead.reason})`;for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension)}continue}let records=recordsRead.value;for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record3)=>record3.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record3.status))){for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension);continue}for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])if(terminallyFailed.add(dimension),laneRecords.at(-1)?.result?.workflowLaneFailureClass==="contract")contractFailed.add(dimension)}}return{successful:successful2,inFlight,contractFailed,contractRetried,dedicatedSuccessful,terminallyFailed,...delegationReadUncertain?{delegationReadUncertain}:{}}}function hasRevisionIndependentDiscoverySemantics(directory,qualified,state2){let ref=qualified.record.result?.outputRef?.trim();if(!ref)return!1;let artifact=readLaneOutput(directory,ref)?.artifact??null;if(!artifact?.revisionDigest?.trim())return!1;return validatePrReviewDiscoveryLaneCompletion({record:qualified.record,result:qualified.record.result,artifact,expected:{mode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:artifact.revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}}).ok}function latestTypedFailureForBaseDimension(directory,state2,dimension){let latest=null;for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes){if(!((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).includes(dimension))continue;let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")continue;for(let record3 of batchRead.value.filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record3.terminalResult,eventlessFailure=!terminal&&CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record3.status),result=terminal?.result??record3.result,failureClass=result?.workflowLaneFailureClass;if(!terminal&&!eventlessFailure||!failureClass)continue;if((terminal?.status??record3.status)==="completed")continue;let candidate={failureClass,terminalEventId:terminal?terminal.eventId:`eventless:${record3.status}:${result?.digest??""}`,recordedAt:terminal?terminal.recordedAt:record3.completedAt??record3.updatedAt,batchId:batch.batchId,laneId:lane.laneId};if(latest===null||candidate.recordedAt>latest.recordedAt||candidate.recordedAt===latest.recordedAt&&candidate.terminalEventId.localeCompare(latest.terminalEventId)>0)latest=candidate}}return latest}function failureClassFromStructuredUnresolvedReason(reason){switch(reason){case"RESOURCE_LIMIT":return"resource";case"DEADLINE_EXCEEDED":return"deadline";default:return"contract"}}function safeDetailFromStructuredUnresolvedReason(reason){switch(reason){case"NOT_EXECUTED":return"structured receipt reported this lane was never executed";case"PARTIAL_OUTPUT":return"structured receipt reported partial output that could not settle this lane";case"CONTRACT_FAILURE":return"structured receipt reported contract-invalid output for this lane";case"RESOURCE_LIMIT":return"structured receipt reported the lane exhausted its resource budget";case"DEADLINE_EXCEEDED":return"structured receipt reported the lane exceeded its collection deadline";case"STALE_BINDING":return"structured receipt reported stale workflow binding for this lane";case"PARENT_CANCELLED":return"structured receipt reported parent-side cancellation before settlement"}}function latestStructuredReceiptUnresolvedForBaseDimension(directory,state2,revisionDigest,dimension){let latest=null,reviewScope=state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0;for(let batch of state2.prReviewBaseDispatches??[]){let recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain")continue;let records=recordsRead.value;for(let lane of batch.lanes){let ownedWorkflowLanes=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedWorkflowLanes.includes(dimension))continue;for(let record3 of records.filter((candidate)=>candidate.laneId===lane.laneId)){let result=record3.result;if(!result)continue;let structured=validateExactStructuredReceiptCoverage({record:record3,result,artifact:null,expected:{mode:"swarm-pr-review:base",workflowLane:lane.workflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope}});if(structured.status!=="accepted")continue;let unresolved=structured.receipt.envelope.unresolved.find((entry)=>entry.workflowLane===dimension);if(!unresolved)continue;let candidate={failureClass:failureClassFromStructuredUnresolvedReason(unresolved.reason),recordedAt:record3.updatedAt,batchId:batch.batchId,laneId:lane.laneId,safeDetail:safeDetailFromStructuredUnresolvedReason(unresolved.reason)};if(latest===null||candidate.recordedAt>latest.recordedAt||candidate.recordedAt===latest.recordedAt&&`${candidate.batchId}\x00${candidate.laneId}`.localeCompare(`${latest.batchId}\x00${latest.laneId}`)>0)latest=candidate}}}return latest}function coverageDisclosureRelativePath(runId){return path105.join("pr-review",runId,"coverage-disclosure.json")}function derivePrReviewDimensionSettlement(directory,state2,revisionDigest){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest),cancellations=state2.prReviewDimensionCancellations??{},dispatched=new Set,dispatchUncertain=new Set,delegationReadUncertain=attempts.delegationReadUncertain;for(let batch of state2.prReviewBaseDispatches??[]){let recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain"){delegationReadUncertain=`delegation store unreadable after ${recordsRead.attempts} attempts (${recordsRead.reason})`;for(let lane of batch.lanes)for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])dispatchUncertain.add(dimension);continue}for(let lane of batch.lanes){if(!recordsRead.value.some((record3)=>record3.laneId===lane.laneId))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])dispatched.add(dimension)}}let coveredDimensions=[],unresolvedDimensions=[],liveDimensions=[];for(let dimension of PR_REVIEW_BASE_DIMENSION_IDS){if(attempts.successful.has(dimension)){coveredDimensions.push(dimension);continue}if(attempts.inFlight.has(dimension)){liveDimensions.push(dimension);continue}let cancellation=cancellations[dimension];if(cancellation){unresolvedDimensions.push({dimension,terminalState:"CANCELLED",reasonKind:"cancelled",safeDetail:`explicitly cancelled by the audited armed-recovery operation at ${cancellation.cancelledAt}`});continue}let latestFailure=latestTypedFailureForBaseDimension(directory,state2,dimension),latestStructuredUnresolved=latestStructuredReceiptUnresolvedForBaseDimension(directory,state2,revisionDigest,dimension);if(attempts.terminallyFailed.has(dimension)||latestStructuredUnresolved){let unresolvedFailure=latestStructuredUnresolved&&(!latestFailure||latestStructuredUnresolved.recordedAt>=latestFailure.recordedAt)?latestStructuredUnresolved:latestFailure;unresolvedDimensions.push({dimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:unresolvedFailure?.failureClass,terminalEventId:unresolvedFailure&&"terminalEventId"in unresolvedFailure?unresolvedFailure.terminalEventId:void 0,batchId:unresolvedFailure?.batchId,laneId:unresolvedFailure?.laneId,safeDetail:unresolvedFailure&&"safeDetail"in unresolvedFailure?unresolvedFailure.safeDetail:unresolvedFailure?PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[unresolvedFailure.failureClass]:"lane terminated without a typed failure class"});continue}if(dispatched.has(dimension)){liveDimensions.push(dimension);continue}if(dispatchUncertain.has(dimension)){liveDimensions.push(dimension);continue}unresolvedDimensions.push({dimension,terminalState:"NOT_LAUNCHED",reasonKind:"not_launched",safeDetail:"no lane for this dimension was ever dispatched"})}return{kind:coveredDimensions.length===PR_REVIEW_BASE_DIMENSION_IDS.length?"COMPLETE":coveredDimensions.length>0?"PARTIAL":"NO_COVERAGE",coveredDimensions,unresolvedDimensions,liveDimensions,allLaunchedTerminal:liveDimensions.length===0,...delegationReadUncertain?{delegationReadUncertain}:{}}}async function readAndVerifyCoverageDisclosure(directory,state2){let{prReviewPartialBaseCoverage:record3,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state2;if(!record3&&!relativePath&&!expectedDigest)return null;if(!record3||!relativePath||!expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure state is incomplete");let expectedPath=coverageDisclosureRelativePath(record3.runId).split(path105.sep).join("/");if(relativePath!==expectedPath)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure path does not match its bound run");let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES,"PR_REVIEW partial base coverage disclosure");if(createHash51("sha256").update(raw,"utf8").digest("hex")!==expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure digest does not match durable state");let decoded;try{decoded=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure is invalid JSON")}let parsed=PrReviewPartialBaseCoverageRecordSchema.safeParse(decoded);if(!parsed.success||JSON.stringify(parsed.data)!==JSON.stringify(record3))throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure does not match durable state");return normalizePrReviewPartialBaseCoverageRecord(parsed.data)}async function admitPrReviewPartialBaseCoverage(directory,sessionID,runId,unresolvedDimensions){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim());if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)throw Error("BLOCKED: partial base coverage requires an active head-bound PR_REVIEW workflow");let normalizedRunId=PrReviewRunIdSchema.parse(runId);if(state2.prReviewReservedRunId&&state2.prReviewReservedRunId!==normalizedRunId)throw Error("BLOCKED: partial base coverage run does not match the reserved PR-review run");let declared=[...new Set(unresolvedDimensions)];if(declared.length!==unresolvedDimensions.length)throw Error("BLOCKED: partial base coverage unresolved_dimensions contains duplicates");if(declared.length===0)throw Error("BLOCKED: partial base coverage requires at least one unresolved dimension; a fully covered run needs no disclosure");let ctx=await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);if(settlement.liveDimensions.length>0){let liveDeclared=settlement.liveDimensions.filter((dimension)=>declared.includes(dimension));if(liveDeclared.length>0)throw Error(`BLOCKED: partial base coverage dimensions still have in-flight lanes: ${liveDeclared.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}let derivedIds=settlement.unresolvedDimensions.map((entry)=>entry.dimension),declaredSet=new Set(declared),derivedSet=new Set(derivedIds),missingFromDeclaration=derivedIds.filter((dimension)=>!declaredSet.has(dimension)),unknownInDeclaration=declared.filter((dimension)=>!derivedSet.has(dimension));if(missingFromDeclaration.length>0||unknownInDeclaration.length>0||derivedIds.length!==declared.length)throw Error(`BLOCKED: partial base coverage declaration must exactly match the derived terminal settlement; declared: [${declared.join(", ")}]; derived unresolved: [${derivedIds.join(", ")||"(none)"}]`+(unknownInDeclaration.length>0?`; declared-but-not-unresolved: [${unknownInDeclaration.join(", ")}]`:"")+(settlement.liveDimensions.length>0?`; still-live (not settleable): [${settlement.liveDimensions.join(", ")}]`:""));for(let entry of settlement.unresolvedDimensions){if(entry.terminalState==="FAILED"&&!entry.failureClass)throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" lacks a typed terminal failure`);if(entry.terminalState==="CANCELLED"&&!state2.prReviewDimensionCancellations?.[entry.dimension])throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" declared CANCELLED without a persisted cancellation record`)}let existing=await readAndVerifyCoverageDisclosure(directory,state2);if(existing){if(existing.runId===normalizedRunId&&existing.prHeadSha===state2.prHeadSha&&existing.revisionDigest===ctx.revisionDigest&&JSON.stringify(existing.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions))return state2;throw Error("BLOCKED: partial base coverage admission differs from the immutable existing disclosure")}let record3={schemaVersion:2,runId:normalizedRunId,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path105.sep).join("/"),absolutePath=validateSwarmPath(directory,relativePath),raw=JSON.stringify(record3,null,2);if(Buffer.byteLength(raw,"utf8")>PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES)throw Error("BLOCKED: partial base coverage disclosure exceeds its write bound");let disclosureWasMissing=!1,removeNewDisclosure=async()=>{if(!disclosureWasMissing)return;try{if(await fsp7.readFile(absolutePath,"utf8")===raw)await fsp7.rm(absolutePath,{force:!0})}catch{}};try{if(readFileSync41(absolutePath,"utf8")!==raw)throw Error("BLOCKED: partial base coverage disclosure path already contains different content")}catch(error93){if(error93.code==="ENOENT"){disclosureWasMissing=!0;try{await writeAtomicJson2(directory,absolutePath,record3)}catch(writeError){throw await removeNewDisclosure(),writeError}}else throw error93}let digest3=createHash51("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:record3,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:digest3})}catch(error93){throw await removeNewDisclosure(),error93}})}async function rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,options){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record3=state2?.prReviewPartialBaseCoverage;if(!state2||!record3||record3.runId!==options.runId)return!1;if((state2.prReviewArtifactBoundaries??[]).includes(options.boundary))return!1;if(state2.prReviewCoverageDisclosurePath!==options.relativePath||state2.prReviewCoverageDisclosureDigest!==options.digest)return!1;let absolutePath=validateSwarmPath(directory,options.relativePath);try{let raw=await fsp7.readFile(absolutePath,"utf8");if(createHash51("sha256").update(raw,"utf8").digest("hex")!==options.digest)return!1}catch(error93){if(error93.code!=="ENOENT")throw error93}return await fsp7.rm(absolutePath,{force:!0}),await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:void 0,prReviewCoverageDisclosurePath:void 0,prReviewCoverageDisclosureDigest:void 0}),!0})}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state2=await requireBoundState(directory,sessionID,"PR_REVIEW");if((state2.prReviewBaseDispatches??[]).length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);if(settlement.kind==="COMPLETE")return{state:state2,settlement};if(settlement.liveDimensions.length>0)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${settlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`);let disclosure=await readAndVerifyCoverageDisclosure(directory,state2),disclosureIds=(disclosure?.unresolvedDimensions??[]).map((entry)=>entry.dimension),derivedIds=settlement.unresolvedDimensions.map((entry)=>entry.dimension);if(disclosure&&JSON.stringify(disclosureIds)===JSON.stringify(derivedIds)&&JSON.stringify(disclosure?.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions)&&disclosure.prHeadSha===state2.prHeadSha&&disclosure.revisionDigest===ctx.revisionDigest&&disclosure.runId===(state2.prReviewArtifactRunId??state2.prReviewReservedRunId))return{state:state2,settlement};let reason=disclosure===null?"no terminal settlement disclosure is admitted; settle via write_pr_review_artifact partial_base_coverage.unresolved_dimensions":disclosureIds.join(",")!==derivedIds.join(",")?`the admitted disclosure [${disclosureIds.join(", ")}] no longer matches the derived terminal settlement [${derivedIds.join(", ")}] — later evidence invalidated it; the disclosure is immutable, so re-run the affected dimensions or restart the review`:"the admitted disclosure no longer matches the derived per-dimension terminal evidence";throw Error(`BLOCKED: PR_REVIEW base coverage is ${settlement.kind} (${settlement.coveredDimensions.length}/${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions covered; unresolved: ${derivedIds.join(", ")||"(none)"}); ${reason}`)}async function readPrReviewTerminalCoverageForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk2(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);return{kind:settlement.kind,coveredDimensions:settlement.coveredDimensions,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),liveDimensions:settlement.liveDimensions,allowedVerdicts:allowedPrReviewReportVerdicts(settlement.kind,[])}}var gateHelpers,PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS,PrReviewUnresolvedDimensionRecordSchema,PrReviewPartialBaseCoverageRecordV2Schema,PrReviewPartialBaseCoverageRecordV1Schema,PrReviewPartialBaseCoverageRecordSchema,PrReviewDimensionCancellationRecordSchema,TERMINAL_FAILED_DELEGATION_STATUSES,PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES=4096;var init_completion=__esm(()=>{init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_utils2();init_circuit();init_finding_policy();init_persistence();PR_REVIEW_REPORT_VERDICTS=["APPROVE","REQUEST_CHANGES","INCOMPLETE"];PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS={contract:"lane failed its output contract after the bounded retry budget was exhausted",resource:"lane exhausted its resource budget before producing valid output",deadline:"lane passed its collection deadline without valid terminal output",liveness:"lane was abandoned by its host (presumed-stale sweep, unobservable host session, or operator cancellation) without an observed agent failure"},PrReviewUnresolvedDimensionRecordSchema=exports_external.object({dimension:exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),terminalState:exports_external.enum(["FAILED","CANCELLED","NOT_LAUNCHED"]),reasonKind:exports_external.enum(["lane_failure","cancelled","not_launched"]),failureClass:exports_external.enum(["contract","resource","deadline","liveness"]).optional(),terminalEventId:exports_external.string().min(1).max(256).optional(),batchId:exports_external.string().min(1).max(128).optional(),laneId:exports_external.string().min(1).max(128).optional(),safeDetail:exports_external.string().max(200).optional()}).strict().superRefine((value,ctx)=>{if(value.terminalState==="FAILED"&&value.reasonKind!=="lane_failure")ctx.addIssue({code:"custom",path:["reasonKind"],message:'FAILED dimensions must use reasonKind "lane_failure"'});if(value.terminalState==="CANCELLED"&&value.reasonKind!=="cancelled"||value.terminalState==="NOT_LAUNCHED"&&value.reasonKind!=="not_launched")ctx.addIssue({code:"custom",path:["reasonKind"],message:`reasonKind must match terminalState "${value.terminalState}"`});if(value.terminalState!=="FAILED"&&(value.failureClass!==void 0||value.terminalEventId!==void 0))ctx.addIssue({code:"custom",path:["failureClass"],message:"failureClass/terminalEventId are legal only on FAILED dimensions"})}),PrReviewPartialBaseCoverageRecordV2Schema=exports_external.object({schemaVersion:exports_external.literal(2),runId:exports_external.string().min(1).max(128),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),unresolvedDimensions:exports_external.array(PrReviewUnresolvedDimensionRecordSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),admittedAt:exports_external.string().datetime()}).strict().superRefine((value,ctx)=>{let seen=new Set;for(let entry of value.unresolvedDimensions){if(seen.has(entry.dimension)){ctx.addIssue({code:"custom",path:["unresolvedDimensions"],message:`must not contain duplicate dimension "${entry.dimension}"`});return}seen.add(entry.dimension)}}),PrReviewPartialBaseCoverageRecordV1Schema=exports_external.object({runId:exports_external.string().min(1).max(128),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),missingDimension:exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),failureClass:exports_external.enum(["contract","resource","deadline"]),terminalEventId:exports_external.string().min(1).max(256),admittedAt:exports_external.string().datetime()}).strict(),PrReviewPartialBaseCoverageRecordSchema=exports_external.union([PrReviewPartialBaseCoverageRecordV2Schema,PrReviewPartialBaseCoverageRecordV1Schema]),PrReviewDimensionCancellationRecordSchema=exports_external.object({reason:exports_external.string().min(1).max(500),cancelledAt:exports_external.string().datetime(),source:exports_external.literal("armed_recovery")}).strict();TERMINAL_FAILED_DELEGATION_STATUSES=CIRCUIT_TERMINAL_DELEGATION_STATUSES});import{createHash as createHash52}from"node:crypto";function bindPrReviewTranscriptAdapterHelpers(helpers){gateHelpers2=helpers}function requireBoundHelpers2(){if(!gateHelpers2)throw Error("BLOCKED: legacy transcript adapter helpers are not bound (the PR workflow gate must bind them at module init)");return gateHelpers2}function derivePrReviewCandidateInventory(directory,state2,ctx){return requireBoundHelpers2().derivePrReviewCandidateInventory(directory,state2,ctx)}function derivePrReviewCriticInventory(directory,state2,ctx){return requireBoundHelpers2().derivePrReviewCriticInventory(directory,state2,ctx)}function authoritativeReviewerClaims(directory,state2,ctx){return requireBoundHelpers2().authoritativeReviewerClaims(directory,state2,ctx)}function reviewerSubagentSessionIds(directory,state2){return requireBoundHelpers2().reviewerSubagentSessionIds(directory,state2)}function prReviewPhaseWindow(state2,phase){return requireBoundHelpers2().prReviewPhaseWindow(state2,phase)}function batchMayContributeClaims(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){return requireBoundHelpers2().batchMayContributeClaims(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)}function recordsPassingBatchIntegrity2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers2().recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function loadArtifactPassingLaneIntegrity(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function reviewerItemBindingKey(itemId){return`${REVIEWER_ITEM_BINDING_KEY_PREFIX}${itemId}`}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bindings=coherence.reviewerItemBindings,bindingKey2=coherence.reviewerItemBindingKeyEncoding==="prefixed-v1"?reviewerItemBindingKey(itemId):itemId,bound=bindings&&Object.hasOwn(bindings,bindingKey2)?bindings[bindingKey2]:void 0,current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function composePrReviewPhaseVerdicts(directory,state2,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state2,ctx):derivePrReviewCriticInventory(directory,state2,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state2,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state2):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state2,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,state2,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=state2.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity2(directory,state2,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state2,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],{markerRows,parsed}=parsePrReviewVerdictRows(artifact.text,declaredItems,phase,reviewerClaims);if(!verdictRowsContainOnlyAssignedIds(markerRows,declaredItems)){appendCompositionDiagnostic(diagnostics,`${phase} lane "${qualified.expectedLane.laneId}" contains an unassigned verdict row; it contributes no claims`);continue}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 indexVerdictRows(text,marker){let markerRows=[],rowsByItemId=new Map,recoveries=[];for(let line of text.split(/\r?\n/)){let row=parsePrReviewVerdictRow(line,marker==="[REVIEWED]"?"reviewer":"critic");if(!row)continue;let fields=row.fields;if(row.recoveredOverflow){let recovery=row.overflowClass,itemId2=fields[1]??"(missing)";recoveries.push({marker,itemId:itemId2,recovery}),warn("PR_REVIEW recovered a legacy verdict row with unescaped pipe overflow",{marker,itemId:itemId2,recovery}),emit("verdict_row_pipe_recovery",{marker,itemId:itemId2,recovery,fieldCount:fields.length})}markerRows.push(fields);let itemId=fields[1]??"",rows=rowsByItemId.get(itemId);if(rows)rows.push(fields);else rowsByItemId.set(itemId,[fields])}return{markerRows,rowsByItemId,recoveries}}function validateReviewerVerdictFields(fields){let parsed=PrReviewReviewerVerdictFieldsSchema.safeParse(fields);return parsed.success?[...parsed.data]:null}function reviewerVerdictRowDigest(fields){return createHash52("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){return parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims).parsed}function parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims){let parsed=new Map,marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",{markerRows,rowsByItemId,recoveries}=indexVerdictRows(text,marker);for(let itemId of itemIds){if(itemId===PR_REVIEW_DISCARDED_EXAMPLE_ITEM_ID)continue;if(phase==="reviewer"){let rows2=rowsByItemId.get(itemId),fields=rows2?.length===1?validateReviewerVerdictFields(rows2[0]):null;if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],riskImpact:fields[10],riskTags:parsePrReviewRiskTagsField(fields[11]??""),rowDigest:reviewerVerdictRowDigest(fields)});continue}let rows=rowsByItemId.get(itemId),verdict=rows?.length===1?validateCriticVerdictFields(rows[0],reviewerClaims?.get(itemId)?.severity):null;if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return{markerRows,parsed,recoveries}}function analyzePrReviewVerdictRowContract(text,itemIds,phase,reviewerClaims){let marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",assigned=new Set(itemIds),{markerRows,parsed,recoveries}=parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims),observedIds=markerRows.map((fields)=>fields[1]||"(missing)"),unexpectedIds=[...new Set(observedIds.filter((itemId)=>!assigned.has(itemId)))],invalidOrMissingIds=itemIds.filter((itemId)=>!parsed.has(itemId));return{ok:verdictRowIdsMatchExactly(markerRows,itemIds)&&invalidOrMissingIds.length===0,expected:`exactly one parseable ${marker} row for assigned IDs ${JSON.stringify(itemIds)} and no other ${marker} IDs`,actual:JSON.stringify({rowCount:markerRows.length,observedIds,invalidOrMissingIds,unexpectedIds}),recoveries}}function verdictRowIdsMatchExactly(markerRows,itemIds){if(itemIds.length===0||markerRows.length!==itemIds.length)return!1;let assigned=new Set(itemIds);if(assigned.size!==itemIds.length)return!1;let observed=new Set;for(let fields of markerRows){let itemId=fields[1]??"";if(!assigned.has(itemId)||observed.has(itemId))return!1;observed.add(itemId)}return observed.size===assigned.size}function verdictRowsContainOnlyAssignedIds(markerRows,itemIds){if(itemIds.length===0)return!1;let assigned=new Set(itemIds);return markerRows.every((fields)=>assigned.has(fields[1]??""))}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=indexVerdictRows(text,"[CRITIC]").rowsByItemId.get(itemId);if(!rows||rows.length!==1)return null;return validateCriticVerdictFields(rows[0],reviewerSeverity)}function validateCriticVerdictFields(fields,reviewerSeverity){let parsed=PrReviewCriticVerdictFieldsSchema.safeParse(fields);if(!parsed.success)return null;let verdict=parsed.data;if(reviewerSeverity){let reviewerRank=REVIEW_SEVERITY_RANK.get(reviewerSeverity),criticRank=REVIEW_SEVERITY_RANK.get(verdict[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(verdict[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(verdict[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}return{status:verdict[2],severity:verdict[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,state2,batchId,laneId,itemIds){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: delegation store unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); feedback artifact coverage for batch ${batchId} is UNKNOWN, not absent. Restore the store and re-validate.`);let record3=batchRead.value.find((candidate)=>candidate.laneId===laneId),ref=record3?.result?.outputRef?.trim()??record3?.terminalResult?.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 feedbackArtifactTextCoversItems(text,itemIds){let rows=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,state2){let classifications=new Map;for(let record3 of state2.prFeedbackVerifications??[])for(let ownership of record3.ownership){let batchRead=findByBatchIdDetailed(directory,record3.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: delegation store unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); settled feedback classifications for batch ${record3.batchId} are UNKNOWN, not absent. Restore the store and re-validate.`);let delegation=batchRead.value.find((candidate)=>candidate.laneId===ownership.laneId),ref=delegation?.result?.outputRef?.trim()??delegation?.terminalResult?.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}var gateHelpers2,REVIEW_SEVERITY_RANK,FEEDBACK_CLASSIFICATIONS,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,REVIEWER_ITEM_BINDING_KEY_PREFIX="item:",analyzeLegacyVerdictRowContract,legacyArtifactHasExactPositiveVerdictRow,legacyFeedbackArtifactCoversItems,legacyFeedbackArtifactTextCoversItems,readLegacySettledFeedbackClassifications,legacyTranscriptAdapterTestSurface;var init_legacy_transcript_adapter=__esm(()=>{init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_telemetry();init_logger();REVIEW_SEVERITY_RANK=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);analyzeLegacyVerdictRowContract=analyzePrReviewVerdictRowContract,legacyArtifactHasExactPositiveVerdictRow=artifactHasExactPositiveVerdictRow,legacyFeedbackArtifactCoversItems=feedbackArtifactCoversItems,legacyFeedbackArtifactTextCoversItems=feedbackArtifactTextCoversItems,readLegacySettledFeedbackClassifications=readSettledFeedbackClassifications,legacyTranscriptAdapterTestSurface={pipeFieldsCapped,indexVerdictRows,reviewerVerdictRowDigest,analyzePrReviewVerdictRowContract,parseLaneItemVerdicts}});function applied(state2,effects=[]){return{status:"applied",state:state2,effects}}function rejected(state2,code,detail){return{status:"rejected",state:state2,rejection:{code,detail}}}function currentGeneration(state2){return state2.revision}function circuitRecordOf(state2){let circuit=state2.prReviewResilience?.circuit;if(!circuit||!("version"in circuit))return null;return circuit}function withCircuit(state2,circuit){if(!state2.prReviewResilience)return state2;return{...state2,prReviewResilience:{...state2.prReviewResilience,circuit}}}function reducePrReviewEvent(state2,event){switch(event.type){case"base_admission_requested":{let dispatches=state2.prReviewBaseDispatches??[];if(dispatches.length>=event.maxBatches)return rejected(state2,"base_batch_limit_reached",`PR_REVIEW base batch limit reached (${dispatches.length} >= ${event.maxBatches})`);let record3={batchId:event.batchId,lanes:event.lanes,validatedAt:event.validatedAt},nextDispatches=[...dispatches,record3];return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record3},[{kind:"persist_state"}])}case"base_admission_rolled_back":{let dispatches=state2.prReviewBaseDispatches??[];if(dispatches.at(-1)?.batchId!==event.batchId)return rejected(state2,"rollback_preconditions_failed",`the last admitted base batch is not ${event.batchId}`);if(event.batchDelegationRecordsExist)return rejected(state2,"rollback_preconditions_failed",`base batch ${event.batchId} already has delegation records`);let nextDispatches=dispatches.slice(0,-1);return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:dispatches.at(-2)},[{kind:"persist_state"}])}case"collection_observed":return applied(state2,[{kind:"emit_diagnostic",source:"collection_observer",code:`collection_${event.diagnostic}`,boundedDetail:event.boundedDetail}]);case"lane_structured_result_submitted":{if(event.generation!==currentGeneration(state2))return rejected(state2,"stale_generation_result",`result generation ${event.generation} does not match the active generation ${currentGeneration(state2)}`);if(event.existingReceiptDigest!==void 0){if(event.existingReceiptDigest===event.semanticEnvelopeDigest)return applied(state2,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed",replay:!0}]);return rejected(state2,"duplicate_conflicting_result",`lane ${event.laneId} already carries a different structured receipt`)}if(event.outcome==="INCOMPLETE")return applied(state2);return applied(state2,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed"}])}case"circuit_advance_requested":{let adoption=adoptPrReviewCircuit(state2.prReviewResilience?.circuit,event.nowMs),circuit=null;if(adoption.kind==="v2"||adoption.kind==="migrated")circuit=adoption.record;let decision=advancePrReviewCircuit(circuit,{nowMs:event.nowMs,threshold:event.policy.correlatedFailureThreshold,openDurationMs:event.policy.circuitOpenDurationMs??resolvePrReviewResiliencePolicy().circuitOpenDurationMs??60000,admission:event.admission,laneSignals:event.laneSignals,probeObservation:event.probeObservation}),effects=[],next=state2;if(adoption.kind==="migrated")next=withCircuit(state2,adoption.record);if(decision.changed&&decision.record){if(next=withCircuit(next,decision.record),decision.action!=="admit_as_probe")effects.push({kind:"persist_state"})}if(decision.action==="block")effects.push({kind:"block_dispatch",reason:decision.reason});return applied(next,effects)}case"circuit_probe_settled":{let circuit=circuitRecordOf(state2);if(!circuit||circuit.state!=="HALF_OPEN"||!circuit.probe)return applied(state2);if(event.outcome.result==="rolled_back_admission")return applied(withCircuit(state2,rollbackPrReviewCircuitProbe(circuit,event.nowMs,event.policy.circuitOpenDurationMs??60000)),[{kind:"persist_state"}]);return applied(state2)}case"resilience_config_changed":{if(!event.enabled){if(!state2.prReviewResilience)return applied(state2);if(state2.prReviewResilience.policy.enabled===!1)return applied(state2);return applied({...state2,prReviewResilience:{...state2.prReviewResilience,policy:{...state2.prReviewResilience.policy,enabled:!1}}},[{kind:"persist_state"}])}let policy=resolvePrReviewResiliencePolicy(event.policy);return applied({...state2,prReviewResilience:{policy,attempts:[],circuit:resetPrReviewResilienceForReEnable({previousCircuit:circuitRecordOf(state2),policy,nowMs:event.nowMs})}},[{kind:"persist_state"}])}case"coverage_finalization_requested":{let{settlement}=event;if(settlement.liveDimensions.length>0)return rejected(state2,"live_lane_blocks_coverage",`coverage finalization blocked by live dimension(s): ${settlement.liveDimensions.join(", ")}`);let verdict=event.requestedVerdict;if(verdict!==void 0){if(settlement.kind==="PARTIAL"&&verdict==="APPROVE")return rejected(state2,"partial_coverage_cannot_approve",`a partial review can never emit ${verdict}`);if(settlement.kind==="NO_COVERAGE"&&verdict!=="INCOMPLETE")return rejected(state2,"no_coverage_requires_incomplete",`a zero-coverage review must report INCOMPLETE, not ${verdict}`)}return applied(state2)}case"critic_result_recorded":{let settledFindingIds=new Set(event.criticSettledReceipts.filter((receipt)=>receipt.status==="UPHELD"||receipt.status==="DOWNGRADED"||receipt.status==="DISPROVED").map((receipt)=>receipt.findingId)),unfulfilled=event.criticRequiredFindingIds.filter((id)=>!settledFindingIds.has(id));if(unfulfilled.length>0)return rejected(state2,"critic_required_unfulfilled",`critic confirmation missing for finding(s): ${unfulfilled.join(", ")}`);return applied(state2)}case"armed_recovery_requested":{let reason=bindingRejection(state2,event);if(reason)return rejected(state2,"stale_foreign_authorization",reason.detail);let cancellations={...state2.prReviewDimensionCancellations??{}};for(let dimension of event.dimensionsToCancel)cancellations[dimension]={reason:event.reason,cancelledAt:event.nowIso,source:"armed_recovery"};return applied({...state2,prReviewDimensionCancellations:cancellations},[{kind:"persist_state"}])}default:{let exhausted=event;return rejected(state2,"unknown_event",`unknown PR-review event discriminant: ${event.type??"(none)"}`)}}}function bindingRejection(state2,event){let binding=event.binding;if(binding.sessionID!==state2.sessionID)return{detail:`authorization session ${binding.sessionID} is foreign to the active workflow session`};if(binding.workflowInstanceId!==void 0&&state2.workflowInstanceId!==void 0&&binding.workflowInstanceId!==state2.workflowInstanceId)return{detail:"authorization belongs to a different workflow instance"};if(!state2.prHeadSha||binding.prHeadSha!==state2.prHeadSha)return{detail:`authorization head ${binding.prHeadSha} does not match the bound head`};if(binding.generation!==currentGeneration(state2))return{detail:`authorization generation ${binding.generation} is stale (active: ${currentGeneration(state2)})`};return null}var init_reducer=__esm(()=>{init_circuit()});function classifyLaneLivenessCondition(input){if(input.recordStatus==="error")return"completed_failure";let sessionLiveOrUnknown=input.sessionStatusType===void 0||input.sessionStatusType==="busy"||input.sessionStatusType==="retry";if(input.waitBudgetExpired&&sessionLiveOrUnknown)return"observer_deadline";if(input.sessionStatusType==="retry")return"provider_retry_in_flight";if(input.exceededEffectiveHorizon)return"execution_deadline";return"idle_failed_child"}function resolveEffectivePrLaneHorizonMs(watchdog,backgroundPendingTimeoutMs){let watchdogOwnsHorizon=watchdog?.enabled===!0&&(watchdog.timeout_ms??0)>0,horizonMs=watchdogOwnsHorizon?watchdog?.timeout_ms:DEFAULT_STALE_DELEGATION_TIMEOUT_MS;return{horizonMs,source:watchdogOwnsHorizon?"watchdog-timeout":"reachability-floor",conflictDisclosed:backgroundPendingTimeoutMs!==void 0&&backgroundPendingTimeoutMs>0&&backgroundPendingTimeoutMs!==horizonMs}}function laneLivenessWatchdogFeatures(watchdog){let enabled=watchdog?.enabled===!0;return{deadlineActive:enabled&&(watchdog?.timeout_ms??0)>0,stallActive:enabled&&(watchdog?.stall_threshold_ms??0)>0&&(watchdog?.stall_min_steps??0)>0&&(watchdog?.stall_token_threshold??0)>0}}var LANE_LIVENESS_WATCHDOG_DEFAULTS,MAX_LANE_LIVENESS_DISCLOSED_IDS=10,ZERO_LANE_ACTIVITY,defaultReadLaneActivity=()=>ZERO_LANE_ACTIVITY;var init_lane_liveness_watchdog=__esm(()=>{init_pending_delegations();init_schema();LANE_LIVENESS_WATCHDOG_DEFAULTS=LaneLivenessWatchdogConfigSchema.parse({});ZERO_LANE_ACTIVITY={stepsObserved:0,estimatedTokens:0}});var exports_pr_workflow_gate={};__export(exports_pr_workflow_gate,{writePrWorkflowAtomicJson:()=>writePrWorkflowAtomicJson,withPrWorkflowCheckoutPreparationLock:()=>withPrWorkflowCheckoutPreparationLock,withPrWorkflowCheckoutMutationLock:()=>withPrWorkflowCheckoutMutationLock,withInactivePrWorkflowCheckoutRestoreLock:()=>withInactivePrWorkflowCheckoutRestoreLock,validatePrWorkflowTransportRecovery:()=>validatePrWorkflowTransportRecovery,validatePrReviewDiscoveryLaneCompletion:()=>validatePrReviewDiscoveryLaneCompletion2,validatePrFeedbackScopeBinding:()=>validatePrFeedbackScopeBinding,transitionPrReviewToFeedback:()=>transitionPrReviewToFeedback,terminalizePrWorkflowGateForSession:()=>terminalizePrWorkflowGateForSession2,submitPrReviewResult:()=>submitPrReviewResult,settlePresumedStalePrWorkflowLanes:()=>settlePresumedStalePrWorkflowLanes,rollbackPrReviewPartialBaseCoverageAdmission:()=>rollbackPrReviewPartialBaseCoverageAdmission,rollbackPrReviewBaseAdmissionIfUnlaunched:()=>rollbackPrReviewBaseAdmissionIfUnlaunched,resolvePrReviewWriterRunId:()=>resolvePrReviewWriterRunId,resolvePrFeedbackScopeDeclaration:()=>resolvePrFeedbackScopeDeclaration,reserveActivePrReviewReentryAuthorization:()=>reserveActivePrReviewReentryAuthorization,recoverArmedPrWorkflow:()=>recoverArmedPrWorkflow,recordPrReviewValidationBatch:()=>recordPrReviewValidationBatch,recordPrFeedbackStageA:()=>recordPrFeedbackStageA,recordPrFeedbackPushAttemptResult:()=>recordPrFeedbackPushAttemptResult,recordPrFeedbackGateBatch:()=>recordPrFeedbackGateBatch,rebindPrFeedbackHead:()=>rebindPrFeedbackHead,readPrWorkflowGateStateForRecovery:()=>readPrWorkflowGateStateForRecovery,readPrWorkflowGateState:()=>readPrWorkflowGateState,readPrReviewTerminalCoverageForReport:()=>readPrReviewTerminalCoverageForReport,readPrReviewReentryBindingContext:()=>readPrReviewReentryBindingContext,readPrReviewFinalFindingPolicyForReport:()=>readPrReviewFinalFindingPolicyForReport,readAuthoritativePrReviewCriticVerdicts:()=>readAuthoritativePrReviewCriticVerdicts,readAuthoritativePrReviewCriticSettlements:()=>readAuthoritativePrReviewCriticSettlements,prWorkflowSessionFileStem:()=>prWorkflowSessionFileStem,prReviewDiscoveryArtifactCoversLane:()=>prReviewDiscoveryArtifactCoversLane,normalizePrWorkflowShellCommand:()=>normalizePrWorkflowShellCommand,normalizePrReviewPartialBaseCoverageRecord:()=>normalizePrReviewPartialBaseCoverageRecord,markPrReviewTriggerEvaluationComplete:()=>markPrReviewTriggerEvaluationComplete,markPrReviewHandoffComplete:()=>markPrReviewHandoffComplete,markPrReviewArtifactBoundary:()=>markPrReviewArtifactBoundary,invalidatePrFeedbackPublication:()=>invalidatePrFeedbackPublication,hasActivePrReviewReentryAuthorization:()=>hasActivePrReviewReentryAuthorization,formatPrReviewLaneValidationFailure:()=>formatPrReviewLaneValidationFailure,findDanglingLivePublicationGeneration:()=>findDanglingLivePublicationGeneration,ensurePrWorkflowSafeParentDirectory:()=>ensurePrWorkflowSafeParentDirectory,enforcePrWorkflowToolBefore:()=>enforcePrWorkflowToolBefore,enforcePrWorkflowDispatchLanesAsync:()=>enforcePrWorkflowDispatchLanesAsync,enforcePrReviewBaseDimensions:()=>enforcePrReviewBaseDimensions,enforcePrFeedbackVerificationOwnership:()=>enforcePrFeedbackVerificationOwnership,describePrWorkflowRevisionDigestFailure:()=>describePrWorkflowRevisionDigestFailure,describePrWorkflowPublicationSection:()=>describePrWorkflowPublicationSection,declarePrFeedbackScope:()=>declarePrFeedbackScope,declarePrFeedbackInventory:()=>declarePrFeedbackInventory,consumePrFeedbackScopeDeclaration:()=>consumePrFeedbackScopeDeclaration,computePrReviewDepthTier:()=>computePrReviewDepthTier,completePrWorkflow:()=>completePrWorkflow,collectPrWorkflowPendingLaneLiveness:()=>collectPrWorkflowPendingLaneLiveness,clearPrWorkflowGateState:()=>clearPrWorkflowGateState,cancelPrFeedbackPublication:()=>cancelPrFeedbackPublication,bindPrWorkflowHead:()=>bindPrWorkflowHead,bindPrReviewTriggerLedger:()=>bindPrReviewTriggerLedger,bindPrReviewBase:()=>bindPrReviewBase,assertPrReviewValidationSettled:()=>assertPrReviewValidationSettled,assertPrReviewCleanCheckout:()=>assertPrReviewCleanCheckout,assertPrReviewBaseCoverageSettled:()=>assertPrReviewBaseCoverageSettled2,assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts:()=>assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts,assertPrReviewArtifactBoundary:()=>assertPrReviewArtifactBoundary,assertPrFeedbackVerificationSettled:()=>assertPrFeedbackVerificationSettled,assertPrFeedbackReadyToPublish:()=>assertPrFeedbackReadyToPublish,assertPrFeedbackGatePhaseSettled:()=>assertPrFeedbackGatePhaseSettled,assertCurrentCheckoutHead:()=>assertCurrentCheckoutHead,allowedPrReviewReportVerdicts:()=>allowedPrReviewReportVerdicts,admitPrReviewPartialBaseCoverage:()=>admitPrReviewPartialBaseCoverage2,activatePrWorkflow:()=>activatePrWorkflow,abortPrWorkflow:()=>abortPrWorkflow,_test_exports:()=>_test_exports2,PrWorkflowCheckoutMutationTimeoutError:()=>PrWorkflowCheckoutMutationTimeoutError,PrReviewResilienceRetryExhaustedError:()=>PrReviewResilienceRetryExhaustedError,PrReviewResilienceCircuitOpenError:()=>PrReviewResilienceCircuitOpenError,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR:()=>PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_REQUIRED_MICRO_LANE_IDS:()=>PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_REPORT_VERDICTS:()=>PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_MICRO_LANE_FLOORS:()=>PR_REVIEW_MICRO_LANE_FLOORS,PR_REVIEW_DEPTH_TIER_THRESHOLDS:()=>PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS:()=>PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_BASE_DIMENSION_IDS:()=>PR_REVIEW_BASE_DIMENSION_IDS,MAX_SALVAGED_SCHEMA_ERROR_CHARS:()=>MAX_SALVAGED_SCHEMA_ERROR_CHARS,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS:()=>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS});import{createHash as createHash53,randomUUID as randomUUID17}from"node:crypto";import{readFileSync as readFileSync42,statSync as statSync39}from"node:fs";import*as fsp8 from"node:fs/promises";import*as path106 from"node:path";function readPrWorkflowGateStateFromDisk3(directory,sessionID){return readPrWorkflowGateStateFromDisk(directory,sessionID)}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(state2){let evidence2=JSON.stringify({operations:state2.evidence.operations,unmerged_codes:state2.evidence.unmergedCodes,paths:state2.evidence.paths,paths_truncated:state2.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state2.code} retryable=false required_action=${state2.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state2){if(state2.kind!=="recovery-required"&&state2.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state2.code,retryable:!1,requiredAction:state2.requiredAction,evidence:state2.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_exports2.classifyPrWorkflowGitStateAsync(directory):null;return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let existing=await readPrWorkflowGateStateFromDisk3(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_exports2.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path106.join(".swarm",workflowCheckoutMutationLockRelativePath()),path106.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:randomUUID17(),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),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state2)rememberState(directory,state2);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state2}function isLivenessTerminalLaneRecord(record3){if(record3.status!=="cancelled"&&record3.status!=="stale"&&record3.status!=="error")return!1;return record3.terminalResult?.result.workflowLaneFailureClass==="liveness"||record3.result?.workflowLaneFailureClass==="liveness"}async function submitPrReviewResult(directory,childSessionId,input){let child=childSessionId.trim(),parsedResult=PrReviewLaneResultEnvelopeSchema.safeParse(input.result);if(!child||!parsedResult.success)return{status:"rejected",reason:"invalid child session or result envelope"};let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return{status:"rejected",reason:`delegation store unreadable after ${childRead.attempts} attempts; child lookup uncertain (${childRead.reason})`};let preliminary=childRead.records.filter((record4)=>record4.subagentSessionId===child&&record4.correlationId===child&&(record4.mode==="swarm-pr-review:base"||record4.mode==="swarm-pr-review:micro")),repairRecord=null;if(preliminary.length!==1){let repairCandidates=childRead.records.filter((candidate)=>candidate.parentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")&&(input.batchId===void 0||input.batchId===candidate.batchId)&&(input.laneId===void 0||input.laneId===candidate.laneId)&&isLivenessTerminalLaneRecord(candidate));if(repairCandidates.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};if(repairRecord=repairCandidates[0],parsedResult.data.outcome!=="INCOMPLETE")return{status:"rejected",reason:"architect-parent repair may only record an unresolved-terminal (INCOMPLETE) outcome"}}let parentSessionId=(repairRecord??preliminary[0]).parentSessionId,record3=repairRecord??preliminary[0],childOfRecord=record3.subagentSessionId;if(!record3.batchId||!record3.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record3.batchId||input.laneId!==void 0&&input.laneId!==record3.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record3;return withSessionStateMutation(directory,parentSessionId,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state2||state2.mode!=="PR_REVIEW"||!state2.workflowInstanceId||!state2.prHeadSha||!state2.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state2)).revisionDigest!==input.revisionDigest)return{status:"rejected",reason:"stale dispatch revision digest"};let dispatchWorkflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),dispatchWorkflowRevision=record3.workflowGeneration;if(!dispatchWorkflowInstanceId||dispatchWorkflowRevision===void 0)return{status:"rejected",reason:"delegation workflow binding provenance is missing"};if(dispatchWorkflowInstanceId!==state2.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};if(repairRecord&&dispatchWorkflowRevision!==state2.revision)return{status:"rejected",reason:`superseded workflow generation binding (delegation generation ${dispatchWorkflowRevision}, active generation ${state2.revision})`};if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record3.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:[];if(!record3.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record3.result?.prReviewResultReceipt?.semanticEnvelopeDigest,submission=reducePrReviewEvent(state2,{type:"lane_structured_result_submitted",batchId,laneId,generation:state2.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{},...repairRecord?{submittedBy:"workflow_parent"}:{}});if(submission.status==="rejected")return{status:"rejected",reason:submission.rejection.code==="duplicate_conflicting_result"?"a different bound receipt is already recorded":`structured result submission rejected: ${submission.rejection.code}`};let published=await publishPrReviewResultReceipt(directory,{parentSessionId,childSessionId:childOfRecord,batchId,laneId,expectedWorkflowInstanceId:state2.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state2.prReviewBaseSha,...repairRecord?{parentRepair:!0}:{},receipt:{schemaVersion:1,mode:record3.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record3.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record3.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record3.status}:{}}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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(state2.prHeadSha)throw Error(`BLOCKED: ${state2.mode} checkout preparation is allowed only before the PR head is bound`);return action2(state2,{markRecoveryRequired:async(gitState)=>{let nextState={...state2,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state2,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk3(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),action2()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp8.opendir(gateDirectory)}catch(error93){if(error93.code==="ENOENT")return;throw error93}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 statePath2=validateSwarmPath(directory,path106.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path106.basename(workflowGateStateRelativePath(state2.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");let boundedEntryName=entry.name.length<=MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS?entry.name:`${entry.name.slice(0,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS-1)}…`;throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state2.sessionID}" has an active ${state2.mode} workflow (state entry "${boundedEntryName}"). For the owning session, run \`/swarm abort-pr-workflow ${state2.mode} <reason...>\` to recover the stuck gate.`)}}catch(error93){scanError=error93}finally{try{await handle.close()}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")closeError=error93}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,options={}){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=options.allowSalvagedRead?(await readPrWorkflowGateStateForRecovery(directory,normalizedSessionID))?.state??null:await readPrWorkflowGateStateFromDisk3(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")}await deleteStateWhileLocked(directory,normalizedSessionID,{expectedStateRevision:expectedRevision,allowSalvagedRead:options.allowSalvagedRead})})}async function terminalizePrWorkflowGateForSession2(directory,sessionID){return terminalizePrWorkflowGateForSession(directory,sessionID)}function isLiveSessionStatusType(type){return LIVE_SESSION_STATUS_TYPES.has(type)}async function probePrWorkflowLaneSessionStatusTypes(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),statusOp=session?.status;if(!session||typeof statusOp!=="function")return{statuses:new Map,degradedReason:"probe-unavailable"};let timeoutError=Error("PR workflow lane liveness probe exceeded its deadline"),response;try{response=await withTimeout((async()=>statusOp.call(session,{query:{directory}}))(),timeoutMs??_test_exports2.laneLivenessProbeTimeoutMs,timeoutError)}catch(error93){return{statuses:new Map,degradedReason:error93===timeoutError?"probe-timeout":"probe-error"}}try{if(response?.error)return{statuses:new Map,degradedReason:"probe-error"};let data=response?.data;if(data===null||data===void 0)return{statuses:new Map,degradedReason:"probe-no-data"};let statuses=new Map;for(let record3 of records){let subagentSessionId=record3.subagentSessionId;if(!subagentSessionId)continue;let type=data[subagentSessionId]?.type;if(typeof type==="string")statuses.set(subagentSessionId,type)}return{statuses}}catch{return{statuses:new Map,degradedReason:"probe-error"}}}async function probeAlivePrWorkflowLaneSessions(directory,records){let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,records);if(probe2.degradedReason)return{alive:new Set,degradedReason:probe2.degradedReason};let alive=new Set;for(let[sessionId,type]of probe2.statuses)if(isLiveSessionStatusType(type))alive.add(sessionId);return{alive}}async function collectPrWorkflowPendingLaneLiveness(directory,records,options={}){let now=0,pastThreshold=[],degraded=(record3,reason)=>({laneId:record3.laneId??record3.correlationId,pendingMs:Math.max(0,now-record3.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record3)=>(record3.status==="pending"||record3.status==="running"||record3.status==="ingesting")&&now-record3.updatedAt>threshold),pastThreshold.length===0)return[];let budgetMs=Math.max(0,Math.min(_test_exports2.laneLivenessProbeTimeoutMs,options.probeBudgetMs??Number.POSITIVE_INFINITY));if(budgetMs<=0)return pastThreshold.map((record3)=>degraded(record3,"probe-skipped-no-budget"));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record3 of pastThreshold){let pendingMs=now-record3.updatedAt,laneId=record3.laneId??record3.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record3.subagentSessionId,type=subagentSessionId?probe2.statuses.get(subagentSessionId):void 0;if(type===void 0){advisories.push({laneId,pendingMs,hostStatus:subagentSessionId?"absent":"unknown",stalledSuspect:!0});continue}advisories.push({laneId,pendingMs,hostStatus:type,stalledSuspect:!isLiveSessionStatusType(type)})}return advisories}catch{return pastThreshold.map((record3)=>degraded(record3,"advisory-unavailable"))}}function describePrWorkflowLaneProbe(settlement){let parts=[];if(settlement.probedAliveLaneIds?.length)parts.push(`liveness probe reports still running: ${settlement.probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`);if(settlement.probeDegradedReason)parts.push(`liveness probe degraded (${settlement.probeDegradedReason})`);return parts.length>0?` (${parts.join("; ")})`:""}function prWorkflowLaneLabel(record3){return record3.laneId??record3.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record3,sessionID){return record3.parentSessionId===sessionID&&record3.mode?.startsWith("swarm-pr-")===!0&&(record3.status==="pending"||record3.status==="running")}async function abortLaneSessionForWatchdog(record3){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record3.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record3.subagentSessionId}}),_test_exports2.laneLivenessProbeTimeoutMs,Error("lane-liveness watchdog abort exceeded its deadline")),!0}catch{return!1}}function lastWatchdogEscalationsByLaneLabel(directory,sessionID){let escalations=new Map,activityObservations=new Map,deadlineLabels=new Set,text="";try{text=readCoreEvents(directory).text}catch{return{escalations,activityObservations,deadlineLabels}}for(let line of text.split(`
|
|
1305
|
+
`).flatMap((line)=>{try{let event=JSON.parse(line);return event.sessionId===sessionId&&event.taskId===taskId?[event]:[]}catch{return[]}}),coverage:read.coverage,truncated:read.truncated}}var FINDING_POLICY_VERSION=1,CONFIDENCE_SCORE,CONFIDENCE_RANK,SEVERITY_RANK,TOKEN_ALIASES,TOKEN_STOPWORDS,MAX_FINDING_SYNTHESIS_CANDIDATES=256,ACTION_RANK,STATUS_RANK;var init_finding_policy=__esm(()=>{init_core_events();init_utils2();init_persistence();CONFIDENCE_SCORE={LOW:0.35,MEDIUM:0.65,HIGH:0.95},CONFIDENCE_RANK={LOW:0,MEDIUM:1,HIGH:2},SEVERITY_RANK={NONE:0,INFO:1,LOW:2,MEDIUM:3,HIGH:4,CRITICAL:5};TOKEN_ALIASES={authorization:"auth",authorized:"auth",authorise:"auth",authorised:"auth",permissions:"permission",checking:"check",checked:"check",checks:"check",reading:"read",reads:"read",requests:"request",path:"endpoint",skips:"skip",skipped:"skip",skipping:"skip"},TOKEN_STOPWORDS=new Set(["the","and","for","with","from","evidence","critic","reviewer","explorer","rationale","reason","change","probe"]);ACTION_RANK={suppress_with_reason:0,report:1,handoff_to_feedback:2,route_to_reviewer:3,route_to_critic:4},STATUS_RANK={DISPROVED:0,PRE_EXISTING:1,NON_ACTIONABLE:1,UNRESOLVED:2,CONFIRMED:3}});import{createHash as createHash51}from"node:crypto";import{readFileSync as readFileSync41}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path105 from"node:path";function bindPrReviewCompletionHelpers(helpers){gateHelpers=helpers}function requireBoundHelpers(){if(!gateHelpers)throw Error("BLOCKED: completion settlement helpers are not bound (the PR workflow gate must bind them at module init)");return gateHelpers}function createPrReviewGateContext(directory,state2){return requireBoundHelpers().createPrReviewGateContext(directory,state2)}function requireBoundState(directory,sessionID,expectedMode){return requireBoundHelpers().requireBoundState(directory,sessionID,expectedMode)}function readPrWorkflowGateStateFromDisk2(directory,sessionID){return requireBoundHelpers().readPrWorkflowGateStateFromDisk(directory,sessionID)}function readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label){return requireBoundHelpers().readBoundedSwarmRegularFile(directory,relativePath,maxBytes,label)}function successfulObligationsFromExactBatch(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics){return requireBoundHelpers().successfulObligationsFromExactBatch(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics)}function recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers().recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function validatePrReviewDiscoveryLaneCompletion(input){return requireBoundHelpers().validatePrReviewDiscoveryLaneCompletion(input)}function validateExactStructuredReceiptCoverage(input){return requireBoundHelpers().validateExactStructuredReceiptCoverage(input)}function allowedPrReviewReportVerdicts(kind,findings=[]){if(kind==="PARTIAL"&&findings.length===0)return["REQUEST_CHANGES","INCOMPLETE"];let supported=evaluateFinalFindingPolicy({policyVersion:1,finalStatus:"COMPLETE",coverage:kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings:[...findings]}).permittedVerdicts.filter((value)=>(value==="APPROVE"||value==="REQUEST_CHANGES"||value==="INCOMPLETE")&&(kind==="COMPLETE"||value!=="APPROVE"));return supported.length>0?supported:["INCOMPLETE"]}function normalizePrReviewPartialBaseCoverageRecord(record3){if("missingDimension"in record3)return{schemaVersion:2,runId:record3.runId,prHeadSha:record3.prHeadSha,revisionDigest:record3.revisionDigest,unresolvedDimensions:[{dimension:record3.missingDimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:record3.failureClass,terminalEventId:record3.terminalEventId,safeDetail:PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[record3.failureClass]}],admittedAt:record3.admittedAt};return record3}function summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest){let successful2=new Set,inFlight=new Set,contractFailed=new Set,contractRetried=new Set(state2.prReviewContractRetryDimensions??[]),dedicatedSuccessful=new Set,terminallyFailed=new Set,delegationReadUncertain;for(let batch of state2.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)successful2.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 semanticallyValidLaneIds=new Set(recordsPassingBatchIntegrity(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified,state2)).map((qualified)=>qualified.record.laneId)),recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain"){delegationReadUncertain=`delegation store unreadable after ${recordsRead.attempts} attempts (${recordsRead.reason})`;for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension)}continue}let records=recordsRead.value;for(let lane of batch.lanes){if(semanticallyValidLaneIds.has(lane.laneId))continue;let laneRecords=records.filter((record3)=>record3.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record3.status))){for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])inFlight.add(dimension);continue}for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])if(terminallyFailed.add(dimension),laneRecords.at(-1)?.result?.workflowLaneFailureClass==="contract")contractFailed.add(dimension)}}return{successful:successful2,inFlight,contractFailed,contractRetried,dedicatedSuccessful,terminallyFailed,...delegationReadUncertain?{delegationReadUncertain}:{}}}function hasRevisionIndependentDiscoverySemantics(directory,qualified,state2){let ref=qualified.record.result?.outputRef?.trim();if(!ref)return!1;let artifact=readLaneOutput(directory,ref)?.artifact??null;if(!artifact?.revisionDigest?.trim())return!1;return validatePrReviewDiscoveryLaneCompletion({record:qualified.record,result:qualified.record.result,artifact,expected:{mode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:artifact.revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}}).ok}function latestTypedFailureForBaseDimension(directory,state2,dimension){let latest=null;for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes){if(!((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).includes(dimension))continue;let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")continue;for(let record3 of batchRead.value.filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record3.terminalResult,eventlessFailure=!terminal&&CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record3.status),result=terminal?.result??record3.result,failureClass=result?.workflowLaneFailureClass;if(!terminal&&!eventlessFailure||!failureClass)continue;if((terminal?.status??record3.status)==="completed")continue;let candidate={failureClass,terminalEventId:terminal?terminal.eventId:`eventless:${record3.status}:${result?.digest??""}`,recordedAt:terminal?terminal.recordedAt:record3.completedAt??record3.updatedAt,batchId:batch.batchId,laneId:lane.laneId};if(latest===null||candidate.recordedAt>latest.recordedAt||candidate.recordedAt===latest.recordedAt&&candidate.terminalEventId.localeCompare(latest.terminalEventId)>0)latest=candidate}}return latest}function failureClassFromStructuredUnresolvedReason(reason){switch(reason){case"RESOURCE_LIMIT":return"resource";case"DEADLINE_EXCEEDED":return"deadline";default:return"contract"}}function safeDetailFromStructuredUnresolvedReason(reason){switch(reason){case"NOT_EXECUTED":return"structured receipt reported this lane was never executed";case"PARTIAL_OUTPUT":return"structured receipt reported partial output that could not settle this lane";case"CONTRACT_FAILURE":return"structured receipt reported contract-invalid output for this lane";case"RESOURCE_LIMIT":return"structured receipt reported the lane exhausted its resource budget";case"DEADLINE_EXCEEDED":return"structured receipt reported the lane exceeded its collection deadline";case"STALE_BINDING":return"structured receipt reported stale workflow binding for this lane";case"PARENT_CANCELLED":return"structured receipt reported parent-side cancellation before settlement"}}function latestStructuredReceiptUnresolvedForBaseDimension(directory,state2,revisionDigest,dimension){let latest=null,reviewScope=state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0;for(let batch of state2.prReviewBaseDispatches??[]){let recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain")continue;let records=recordsRead.value;for(let lane of batch.lanes){let ownedWorkflowLanes=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!ownedWorkflowLanes.includes(dimension))continue;for(let record3 of records.filter((candidate)=>candidate.laneId===lane.laneId)){let result=record3.result;if(!result)continue;let structured=validateExactStructuredReceiptCoverage({record:record3,result,artifact:null,expected:{mode:"swarm-pr-review:base",workflowLane:lane.workflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope}});if(structured.status!=="accepted")continue;let unresolved=structured.receipt.envelope.unresolved.find((entry)=>entry.workflowLane===dimension);if(!unresolved)continue;let candidate={failureClass:failureClassFromStructuredUnresolvedReason(unresolved.reason),recordedAt:record3.updatedAt,batchId:batch.batchId,laneId:lane.laneId,safeDetail:safeDetailFromStructuredUnresolvedReason(unresolved.reason)};if(latest===null||candidate.recordedAt>latest.recordedAt||candidate.recordedAt===latest.recordedAt&&`${candidate.batchId}\x00${candidate.laneId}`.localeCompare(`${latest.batchId}\x00${latest.laneId}`)>0)latest=candidate}}}return latest}function coverageDisclosureRelativePath(runId){return path105.join("pr-review",runId,"coverage-disclosure.json")}function derivePrReviewDimensionSettlement(directory,state2,revisionDigest){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest),cancellations=state2.prReviewDimensionCancellations??{},dispatched=new Set,dispatchUncertain=new Set,delegationReadUncertain=attempts.delegationReadUncertain;for(let batch of state2.prReviewBaseDispatches??[]){let recordsRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(recordsRead.status==="uncertain"){delegationReadUncertain=`delegation store unreadable after ${recordsRead.attempts} attempts (${recordsRead.reason})`;for(let lane of batch.lanes)for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])dispatchUncertain.add(dimension);continue}for(let lane of batch.lanes){if(!recordsRead.value.some((record3)=>record3.laneId===lane.laneId))continue;for(let dimension of lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])dispatched.add(dimension)}}let coveredDimensions=[],unresolvedDimensions=[],liveDimensions=[];for(let dimension of PR_REVIEW_BASE_DIMENSION_IDS){if(attempts.successful.has(dimension)){coveredDimensions.push(dimension);continue}if(attempts.inFlight.has(dimension)){liveDimensions.push(dimension);continue}let cancellation=cancellations[dimension];if(cancellation){unresolvedDimensions.push({dimension,terminalState:"CANCELLED",reasonKind:"cancelled",safeDetail:`explicitly cancelled by the audited armed-recovery operation at ${cancellation.cancelledAt}`});continue}let latestFailure=latestTypedFailureForBaseDimension(directory,state2,dimension),latestStructuredUnresolved=latestStructuredReceiptUnresolvedForBaseDimension(directory,state2,revisionDigest,dimension);if(attempts.terminallyFailed.has(dimension)||latestStructuredUnresolved){let unresolvedFailure=latestStructuredUnresolved&&(!latestFailure||latestStructuredUnresolved.recordedAt>=latestFailure.recordedAt)?latestStructuredUnresolved:latestFailure;unresolvedDimensions.push({dimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:unresolvedFailure?.failureClass,terminalEventId:unresolvedFailure&&"terminalEventId"in unresolvedFailure?unresolvedFailure.terminalEventId:void 0,batchId:unresolvedFailure?.batchId,laneId:unresolvedFailure?.laneId,safeDetail:unresolvedFailure&&"safeDetail"in unresolvedFailure?unresolvedFailure.safeDetail:unresolvedFailure?PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[unresolvedFailure.failureClass]:"lane terminated without a typed failure class"});continue}if(dispatched.has(dimension)){liveDimensions.push(dimension);continue}if(dispatchUncertain.has(dimension)){liveDimensions.push(dimension);continue}unresolvedDimensions.push({dimension,terminalState:"NOT_LAUNCHED",reasonKind:"not_launched",safeDetail:"no lane for this dimension was ever dispatched"})}return{kind:coveredDimensions.length===PR_REVIEW_BASE_DIMENSION_IDS.length?"COMPLETE":coveredDimensions.length>0?"PARTIAL":"NO_COVERAGE",coveredDimensions,unresolvedDimensions,liveDimensions,allLaunchedTerminal:liveDimensions.length===0,...delegationReadUncertain?{delegationReadUncertain}:{}}}async function readAndVerifyCoverageDisclosure(directory,state2){let{prReviewPartialBaseCoverage:record3,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state2;if(!record3&&!relativePath&&!expectedDigest)return null;if(!record3||!relativePath||!expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure state is incomplete");let expectedPath=coverageDisclosureRelativePath(record3.runId).split(path105.sep).join("/");if(relativePath!==expectedPath)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure path does not match its bound run");let raw=await readBoundedSwarmRegularFile(directory,relativePath,PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES,"PR_REVIEW partial base coverage disclosure");if(createHash51("sha256").update(raw,"utf8").digest("hex")!==expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure digest does not match durable state");let decoded;try{decoded=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure is invalid JSON")}let parsed=PrReviewPartialBaseCoverageRecordSchema.safeParse(decoded);if(!parsed.success||JSON.stringify(parsed.data)!==JSON.stringify(record3))throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure does not match durable state");return normalizePrReviewPartialBaseCoverageRecord(parsed.data)}async function admitPrReviewPartialBaseCoverage(directory,sessionID,runId,unresolvedDimensions){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim());if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)throw Error("BLOCKED: partial base coverage requires an active head-bound PR_REVIEW workflow");let normalizedRunId=PrReviewRunIdSchema.parse(runId);if(state2.prReviewReservedRunId&&state2.prReviewReservedRunId!==normalizedRunId)throw Error("BLOCKED: partial base coverage run does not match the reserved PR-review run");let declared=[...new Set(unresolvedDimensions)];if(declared.length!==unresolvedDimensions.length)throw Error("BLOCKED: partial base coverage unresolved_dimensions contains duplicates");if(declared.length===0)throw Error("BLOCKED: partial base coverage requires at least one unresolved dimension; a fully covered run needs no disclosure");let ctx=await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);if(settlement.liveDimensions.length>0){let liveDeclared=settlement.liveDimensions.filter((dimension)=>declared.includes(dimension));if(liveDeclared.length>0)throw Error(`BLOCKED: partial base coverage dimensions still have in-flight lanes: ${liveDeclared.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}let derivedIds=settlement.unresolvedDimensions.map((entry)=>entry.dimension),declaredSet=new Set(declared),derivedSet=new Set(derivedIds),missingFromDeclaration=derivedIds.filter((dimension)=>!declaredSet.has(dimension)),unknownInDeclaration=declared.filter((dimension)=>!derivedSet.has(dimension));if(missingFromDeclaration.length>0||unknownInDeclaration.length>0||derivedIds.length!==declared.length)throw Error(`BLOCKED: partial base coverage declaration must exactly match the derived terminal settlement; declared: [${declared.join(", ")}]; derived unresolved: [${derivedIds.join(", ")||"(none)"}]`+(unknownInDeclaration.length>0?`; declared-but-not-unresolved: [${unknownInDeclaration.join(", ")}]`:"")+(settlement.liveDimensions.length>0?`; still-live (not settleable): [${settlement.liveDimensions.join(", ")}]`:""));for(let entry of settlement.unresolvedDimensions){if(entry.terminalState==="FAILED"&&!entry.failureClass)throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" lacks a typed terminal failure`);if(entry.terminalState==="CANCELLED"&&!state2.prReviewDimensionCancellations?.[entry.dimension])throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" declared CANCELLED without a persisted cancellation record`)}let existing=await readAndVerifyCoverageDisclosure(directory,state2);if(existing){if(existing.runId===normalizedRunId&&existing.prHeadSha===state2.prHeadSha&&existing.revisionDigest===ctx.revisionDigest&&JSON.stringify(existing.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions))return state2;throw Error("BLOCKED: partial base coverage admission differs from the immutable existing disclosure")}let record3={schemaVersion:2,runId:normalizedRunId,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path105.sep).join("/"),absolutePath=validateSwarmPath(directory,relativePath),raw=JSON.stringify(record3,null,2);if(Buffer.byteLength(raw,"utf8")>PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES)throw Error("BLOCKED: partial base coverage disclosure exceeds its write bound");let disclosureWasMissing=!1,removeNewDisclosure=async()=>{if(!disclosureWasMissing)return;try{if(await fsp7.readFile(absolutePath,"utf8")===raw)await fsp7.rm(absolutePath,{force:!0})}catch{}};try{if(readFileSync41(absolutePath,"utf8")!==raw)throw Error("BLOCKED: partial base coverage disclosure path already contains different content")}catch(error93){if(error93.code==="ENOENT"){disclosureWasMissing=!0;try{await writeAtomicJson2(directory,absolutePath,record3)}catch(writeError){throw await removeNewDisclosure(),writeError}}else throw error93}let digest3=createHash51("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:record3,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:digest3})}catch(error93){throw await removeNewDisclosure(),error93}})}async function rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,options){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record3=state2?.prReviewPartialBaseCoverage;if(!state2||!record3||record3.runId!==options.runId)return!1;if((state2.prReviewArtifactBoundaries??[]).includes(options.boundary))return!1;if(state2.prReviewCoverageDisclosurePath!==options.relativePath||state2.prReviewCoverageDisclosureDigest!==options.digest)return!1;let absolutePath=validateSwarmPath(directory,options.relativePath);try{let raw=await fsp7.readFile(absolutePath,"utf8");if(createHash51("sha256").update(raw,"utf8").digest("hex")!==options.digest)return!1}catch(error93){if(error93.code!=="ENOENT")throw error93}return await fsp7.rm(absolutePath,{force:!0}),await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:void 0,prReviewCoverageDisclosurePath:void 0,prReviewCoverageDisclosureDigest:void 0}),!0})}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state2=await requireBoundState(directory,sessionID,"PR_REVIEW");if((state2.prReviewBaseDispatches??[]).length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);if(settlement.kind==="COMPLETE")return{state:state2,settlement};if(settlement.liveDimensions.length>0)throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${settlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`);let disclosure=await readAndVerifyCoverageDisclosure(directory,state2),disclosureIds=(disclosure?.unresolvedDimensions??[]).map((entry)=>entry.dimension),derivedIds=settlement.unresolvedDimensions.map((entry)=>entry.dimension);if(disclosure&&JSON.stringify(disclosureIds)===JSON.stringify(derivedIds)&&JSON.stringify(disclosure?.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions)&&disclosure.prHeadSha===state2.prHeadSha&&disclosure.revisionDigest===ctx.revisionDigest&&disclosure.runId===(state2.prReviewArtifactRunId??state2.prReviewReservedRunId))return{state:state2,settlement};let reason=disclosure===null?"no terminal settlement disclosure is admitted; settle via write_pr_review_artifact partial_base_coverage.unresolved_dimensions":disclosureIds.join(",")!==derivedIds.join(",")?`the admitted disclosure [${disclosureIds.join(", ")}] no longer matches the derived terminal settlement [${derivedIds.join(", ")}] — later evidence invalidated it; the disclosure is immutable, so re-run the affected dimensions or restart the review`:"the admitted disclosure no longer matches the derived per-dimension terminal evidence";throw Error(`BLOCKED: PR_REVIEW base coverage is ${settlement.kind} (${settlement.coveredDimensions.length}/${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions covered; unresolved: ${derivedIds.join(", ")||"(none)"}); ${reason}`)}async function readPrReviewTerminalCoverageForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk2(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);return{kind:settlement.kind,coveredDimensions:settlement.coveredDimensions,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),liveDimensions:settlement.liveDimensions,allowedVerdicts:allowedPrReviewReportVerdicts(settlement.kind,[])}}var gateHelpers,PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS,PrReviewUnresolvedDimensionRecordSchema,PrReviewPartialBaseCoverageRecordV2Schema,PrReviewPartialBaseCoverageRecordV1Schema,PrReviewPartialBaseCoverageRecordSchema,PrReviewDimensionCancellationRecordSchema,TERMINAL_FAILED_DELEGATION_STATUSES,PR_REVIEW_COVERAGE_DISCLOSURE_MAX_BYTES=4096;var init_completion=__esm(()=>{init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_utils2();init_circuit();init_finding_policy();init_persistence();PR_REVIEW_REPORT_VERDICTS=["APPROVE","REQUEST_CHANGES","INCOMPLETE"];PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS={contract:"lane failed its output contract after the bounded retry budget was exhausted",resource:"lane exhausted its resource budget before producing valid output",deadline:"lane passed its collection deadline without valid terminal output",liveness:"lane was abandoned by its host (presumed-stale sweep, unobservable host session, or operator cancellation) without an observed agent failure"},PrReviewUnresolvedDimensionRecordSchema=exports_external.object({dimension:exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),terminalState:exports_external.enum(["FAILED","CANCELLED","NOT_LAUNCHED"]),reasonKind:exports_external.enum(["lane_failure","cancelled","not_launched"]),failureClass:exports_external.enum(["contract","resource","deadline","liveness"]).optional(),terminalEventId:exports_external.string().min(1).max(256).optional(),batchId:exports_external.string().min(1).max(128).optional(),laneId:exports_external.string().min(1).max(128).optional(),safeDetail:exports_external.string().max(200).optional()}).strict().superRefine((value,ctx)=>{if(value.terminalState==="FAILED"&&value.reasonKind!=="lane_failure")ctx.addIssue({code:"custom",path:["reasonKind"],message:'FAILED dimensions must use reasonKind "lane_failure"'});if(value.terminalState==="CANCELLED"&&value.reasonKind!=="cancelled"||value.terminalState==="NOT_LAUNCHED"&&value.reasonKind!=="not_launched")ctx.addIssue({code:"custom",path:["reasonKind"],message:`reasonKind must match terminalState "${value.terminalState}"`});if(value.terminalState!=="FAILED"&&(value.failureClass!==void 0||value.terminalEventId!==void 0))ctx.addIssue({code:"custom",path:["failureClass"],message:"failureClass/terminalEventId are legal only on FAILED dimensions"})}),PrReviewPartialBaseCoverageRecordV2Schema=exports_external.object({schemaVersion:exports_external.literal(2),runId:exports_external.string().min(1).max(128),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),unresolvedDimensions:exports_external.array(PrReviewUnresolvedDimensionRecordSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),admittedAt:exports_external.string().datetime()}).strict().superRefine((value,ctx)=>{let seen=new Set;for(let entry of value.unresolvedDimensions){if(seen.has(entry.dimension)){ctx.addIssue({code:"custom",path:["unresolvedDimensions"],message:`must not contain duplicate dimension "${entry.dimension}"`});return}seen.add(entry.dimension)}}),PrReviewPartialBaseCoverageRecordV1Schema=exports_external.object({runId:exports_external.string().min(1).max(128),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),missingDimension:exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),failureClass:exports_external.enum(["contract","resource","deadline"]),terminalEventId:exports_external.string().min(1).max(256),admittedAt:exports_external.string().datetime()}).strict(),PrReviewPartialBaseCoverageRecordSchema=exports_external.union([PrReviewPartialBaseCoverageRecordV2Schema,PrReviewPartialBaseCoverageRecordV1Schema]),PrReviewDimensionCancellationRecordSchema=exports_external.object({reason:exports_external.string().min(1).max(500),cancelledAt:exports_external.string().datetime(),source:exports_external.literal("armed_recovery")}).strict();TERMINAL_FAILED_DELEGATION_STATUSES=CIRCUIT_TERMINAL_DELEGATION_STATUSES});import{createHash as createHash52}from"node:crypto";function bindPrReviewTranscriptAdapterHelpers(helpers){gateHelpers2=helpers}function requireBoundHelpers2(){if(!gateHelpers2)throw Error("BLOCKED: legacy transcript adapter helpers are not bound (the PR workflow gate must bind them at module init)");return gateHelpers2}function derivePrReviewCandidateInventory(directory,state2,ctx){return requireBoundHelpers2().derivePrReviewCandidateInventory(directory,state2,ctx)}function derivePrReviewCriticInventory(directory,state2,ctx){return requireBoundHelpers2().derivePrReviewCriticInventory(directory,state2,ctx)}function authoritativeReviewerClaims(directory,state2,ctx){return requireBoundHelpers2().authoritativeReviewerClaims(directory,state2,ctx)}function reviewerSubagentSessionIds(directory,state2){return requireBoundHelpers2().reviewerSubagentSessionIds(directory,state2)}function prReviewPhaseWindow(state2,phase){return requireBoundHelpers2().prReviewPhaseWindow(state2,phase)}function batchMayContributeClaims(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){return requireBoundHelpers2().batchMayContributeClaims(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)}function recordsPassingBatchIntegrity2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers2().recordsPassingBatchIntegrity(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function loadArtifactPassingLaneIntegrity(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics)}function appendCompositionDiagnostic(diagnostics,message){if(diagnostics.length>=MAX_COMPOSITION_DIAGNOSTICS)return;diagnostics.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS))}function reviewerItemBindingKey(itemId){return`${REVIEWER_ITEM_BINDING_KEY_PREFIX}${itemId}`}function criticClaimIsBoundToCurrentReviewerRow(coherence,itemId,reviewerClaims){let bindings=coherence.reviewerItemBindings,bindingKey2=coherence.reviewerItemBindingKeyEncoding==="prefixed-v1"?reviewerItemBindingKey(itemId):itemId,bound=bindings&&Object.hasOwn(bindings,bindingKey2)?bindings[bindingKey2]:void 0,current=reviewerClaims?.get(itemId)?.rowDigest;return Boolean(bound&¤t&&bound===current)}function composePrReviewPhaseVerdicts(directory,state2,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state2,ctx):derivePrReviewCriticInventory(directory,state2,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state2,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state2):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state2,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,state2,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=state2.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity2(directory,state2,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state2,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],{markerRows,parsed}=parsePrReviewVerdictRows(artifact.text,declaredItems,phase,reviewerClaims);if(!verdictRowsContainOnlyAssignedIds(markerRows,declaredItems)){appendCompositionDiagnostic(diagnostics,`${phase} lane "${qualified.expectedLane.laneId}" contains an unassigned verdict row; it contributes no claims`);continue}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 indexVerdictRows(text,marker){let markerRows=[],rowsByItemId=new Map,recoveries=[];for(let line of text.split(/\r?\n/)){let row=parsePrReviewVerdictRow(line,marker==="[REVIEWED]"?"reviewer":"critic");if(!row)continue;let fields=row.fields;if(row.recoveredOverflow){let recovery=row.overflowClass,itemId2=fields[1]??"(missing)";recoveries.push({marker,itemId:itemId2,recovery}),warn("PR_REVIEW recovered a legacy verdict row with unescaped pipe overflow",{marker,itemId:itemId2,recovery}),emit("verdict_row_pipe_recovery",{marker,itemId:itemId2,recovery,fieldCount:fields.length})}markerRows.push(fields);let itemId=fields[1]??"",rows=rowsByItemId.get(itemId);if(rows)rows.push(fields);else rowsByItemId.set(itemId,[fields])}return{markerRows,rowsByItemId,recoveries}}function validateReviewerVerdictFields(fields){let parsed=PrReviewReviewerVerdictFieldsSchema.safeParse(fields);return parsed.success?[...parsed.data]:null}function reviewerVerdictRowDigest(fields){return createHash52("sha256").update(fields.join("\x00")).digest("hex")}function parseLaneItemVerdicts(text,itemIds,phase,reviewerClaims){return parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims).parsed}function parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims){let parsed=new Map,marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",{markerRows,rowsByItemId,recoveries}=indexVerdictRows(text,marker);for(let itemId of itemIds){if(itemId===PR_REVIEW_DISCARDED_EXAMPLE_ITEM_ID)continue;if(phase==="reviewer"){let rows2=rowsByItemId.get(itemId),fields=rows2?.length===1?validateReviewerVerdictFields(rows2[0]):null;if(!fields)continue;parsed.set(itemId,{classification:fields[2],severity:fields[4],riskImpact:fields[10],riskTags:parsePrReviewRiskTagsField(fields[11]??""),rowDigest:reviewerVerdictRowDigest(fields)});continue}let rows=rowsByItemId.get(itemId),verdict=rows?.length===1?validateCriticVerdictFields(rows[0],reviewerClaims?.get(itemId)?.severity):null;if(!verdict)continue;parsed.set(itemId,{classification:verdict.status,severity:verdict.severity})}return{markerRows,parsed,recoveries}}function analyzePrReviewVerdictRowContract(text,itemIds,phase,reviewerClaims){let marker=phase==="reviewer"?"[REVIEWED]":"[CRITIC]",assigned=new Set(itemIds),{markerRows,parsed,recoveries}=parsePrReviewVerdictRows(text,itemIds,phase,reviewerClaims),observedIds=markerRows.map((fields)=>fields[1]||"(missing)"),unexpectedIds=[...new Set(observedIds.filter((itemId)=>!assigned.has(itemId)))],invalidOrMissingIds=itemIds.filter((itemId)=>!parsed.has(itemId));return{ok:verdictRowIdsMatchExactly(markerRows,itemIds)&&invalidOrMissingIds.length===0,expected:`exactly one parseable ${marker} row for assigned IDs ${JSON.stringify(itemIds)} and no other ${marker} IDs`,actual:JSON.stringify({rowCount:markerRows.length,observedIds,invalidOrMissingIds,unexpectedIds}),recoveries}}function verdictRowIdsMatchExactly(markerRows,itemIds){if(itemIds.length===0||markerRows.length!==itemIds.length)return!1;let assigned=new Set(itemIds);if(assigned.size!==itemIds.length)return!1;let observed=new Set;for(let fields of markerRows){let itemId=fields[1]??"";if(!assigned.has(itemId)||observed.has(itemId))return!1;observed.add(itemId)}return observed.size===assigned.size}function verdictRowsContainOnlyAssignedIds(markerRows,itemIds){if(itemIds.length===0)return!1;let assigned=new Set(itemIds);return markerRows.every((fields)=>assigned.has(fields[1]??""))}function parseCriticVerdict(text,itemId,reviewerSeverity){let rows=indexVerdictRows(text,"[CRITIC]").rowsByItemId.get(itemId);if(!rows||rows.length!==1)return null;return validateCriticVerdictFields(rows[0],reviewerSeverity)}function validateCriticVerdictFields(fields,reviewerSeverity){let parsed=PrReviewCriticVerdictFieldsSchema.safeParse(fields);if(!parsed.success)return null;let verdict=parsed.data;if(reviewerSeverity){let reviewerRank=REVIEW_SEVERITY_RANK.get(reviewerSeverity),criticRank=REVIEW_SEVERITY_RANK.get(verdict[3]);if(reviewerRank===void 0||criticRank===void 0)return null;if(verdict[2]==="UPHELD"&&criticRank!==reviewerRank)return null;if(verdict[2]==="DOWNGRADED"&&criticRank>=reviewerRank)return null}return{status:verdict[2],severity:verdict[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,state2,batchId,laneId,itemIds){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: delegation store unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); feedback artifact coverage for batch ${batchId} is UNKNOWN, not absent. Restore the store and re-validate.`);let record3=batchRead.value.find((candidate)=>candidate.laneId===laneId),ref=record3?.result?.outputRef?.trim()??record3?.terminalResult?.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 feedbackArtifactTextCoversItems(text,itemIds){let rows=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,state2){let classifications=new Map;for(let record3 of state2.prFeedbackVerifications??[])for(let ownership of record3.ownership){let batchRead=findByBatchIdDetailed(directory,record3.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: delegation store unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); settled feedback classifications for batch ${record3.batchId} are UNKNOWN, not absent. Restore the store and re-validate.`);let delegation=batchRead.value.find((candidate)=>candidate.laneId===ownership.laneId),ref=delegation?.result?.outputRef?.trim()??delegation?.terminalResult?.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}var gateHelpers2,REVIEW_SEVERITY_RANK,FEEDBACK_CLASSIFICATIONS,MAX_COMPOSITION_DIAGNOSTICS=16,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS=1000,REVIEWER_ITEM_BINDING_KEY_PREFIX="item:",analyzeLegacyVerdictRowContract,legacyArtifactHasExactPositiveVerdictRow,legacyFeedbackArtifactCoversItems,legacyFeedbackArtifactTextCoversItems,readLegacySettledFeedbackClassifications,legacyTranscriptAdapterTestSurface;var init_legacy_transcript_adapter=__esm(()=>{init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_telemetry();init_logger();REVIEW_SEVERITY_RANK=new Map([["NONE",0],["INFO",1],["LOW",2],["MEDIUM",3],["HIGH",4],["CRITICAL",5]]),FEEDBACK_CLASSIFICATIONS=new Set(["CONFIRMED","PARTIAL","DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"]);analyzeLegacyVerdictRowContract=analyzePrReviewVerdictRowContract,legacyArtifactHasExactPositiveVerdictRow=artifactHasExactPositiveVerdictRow,legacyFeedbackArtifactCoversItems=feedbackArtifactCoversItems,legacyFeedbackArtifactTextCoversItems=feedbackArtifactTextCoversItems,readLegacySettledFeedbackClassifications=readSettledFeedbackClassifications,legacyTranscriptAdapterTestSurface={pipeFieldsCapped,indexVerdictRows,reviewerVerdictRowDigest,analyzePrReviewVerdictRowContract,parseLaneItemVerdicts}});function applied(state2,effects=[]){return{status:"applied",state:state2,effects}}function rejected(state2,code,detail){return{status:"rejected",state:state2,rejection:{code,detail}}}function currentGeneration(state2){return state2.revision}function circuitRecordOf(state2){let circuit=state2.prReviewResilience?.circuit;if(!circuit||!("version"in circuit))return null;return circuit}function withCircuit(state2,circuit){if(!state2.prReviewResilience)return state2;return{...state2,prReviewResilience:{...state2.prReviewResilience,circuit}}}function reducePrReviewEvent(state2,event){switch(event.type){case"base_admission_requested":{let dispatches=state2.prReviewBaseDispatches??[];if(dispatches.length>=event.maxBatches)return rejected(state2,"base_batch_limit_reached",`PR_REVIEW base batch limit reached (${dispatches.length} >= ${event.maxBatches})`);let record3={batchId:event.batchId,lanes:event.lanes,validatedAt:event.validatedAt},nextDispatches=[...dispatches,record3];return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record3},[{kind:"persist_state"}])}case"base_admission_rolled_back":{let dispatches=state2.prReviewBaseDispatches??[];if(dispatches.at(-1)?.batchId!==event.batchId)return rejected(state2,"rollback_preconditions_failed",`the last admitted base batch is not ${event.batchId}`);if(event.batchDelegationRecordsExist)return rejected(state2,"rollback_preconditions_failed",`base batch ${event.batchId} already has delegation records`);let nextDispatches=dispatches.slice(0,-1);return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:dispatches.at(-2)},[{kind:"persist_state"}])}case"collection_observed":return applied(state2,[{kind:"emit_diagnostic",source:"collection_observer",code:`collection_${event.diagnostic}`,boundedDetail:event.boundedDetail}]);case"lane_structured_result_submitted":{if(event.generation!==currentGeneration(state2))return rejected(state2,"stale_generation_result",`result generation ${event.generation} does not match the active generation ${currentGeneration(state2)}`);if(event.existingReceiptDigest!==void 0){if(event.existingReceiptDigest===event.semanticEnvelopeDigest)return applied(state2,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed",replay:!0}]);return rejected(state2,"duplicate_conflicting_result",`lane ${event.laneId} already carries a different structured receipt`)}if(event.outcome==="INCOMPLETE")return applied(state2);return applied(state2,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed"}])}case"circuit_advance_requested":{let adoption=adoptPrReviewCircuit(state2.prReviewResilience?.circuit,event.nowMs),circuit=null;if(adoption.kind==="v2"||adoption.kind==="migrated")circuit=adoption.record;let decision=advancePrReviewCircuit(circuit,{nowMs:event.nowMs,threshold:event.policy.correlatedFailureThreshold,openDurationMs:event.policy.circuitOpenDurationMs??resolvePrReviewResiliencePolicy().circuitOpenDurationMs??60000,admission:event.admission,laneSignals:event.laneSignals,probeObservation:event.probeObservation}),effects=[],next=state2;if(adoption.kind==="migrated")next=withCircuit(state2,adoption.record);if(decision.changed&&decision.record){if(next=withCircuit(next,decision.record),decision.action!=="admit_as_probe")effects.push({kind:"persist_state"})}if(decision.action==="block")effects.push({kind:"block_dispatch",reason:decision.reason});return applied(next,effects)}case"circuit_probe_settled":{let circuit=circuitRecordOf(state2);if(!circuit||circuit.state!=="HALF_OPEN"||!circuit.probe)return applied(state2);if(event.outcome.result==="rolled_back_admission")return applied(withCircuit(state2,rollbackPrReviewCircuitProbe(circuit,event.nowMs,event.policy.circuitOpenDurationMs??60000)),[{kind:"persist_state"}]);return applied(state2)}case"resilience_config_changed":{if(!event.enabled){if(!state2.prReviewResilience)return applied(state2);if(state2.prReviewResilience.policy.enabled===!1)return applied(state2);return applied({...state2,prReviewResilience:{...state2.prReviewResilience,policy:{...state2.prReviewResilience.policy,enabled:!1}}},[{kind:"persist_state"}])}let policy=resolvePrReviewResiliencePolicy(event.policy);return applied({...state2,prReviewResilience:{policy,attempts:[],circuit:resetPrReviewResilienceForReEnable({previousCircuit:circuitRecordOf(state2),policy,nowMs:event.nowMs})}},[{kind:"persist_state"}])}case"coverage_finalization_requested":{let{settlement}=event;if(settlement.liveDimensions.length>0)return rejected(state2,"live_lane_blocks_coverage",`coverage finalization blocked by live dimension(s): ${settlement.liveDimensions.join(", ")}`);let verdict=event.requestedVerdict;if(verdict!==void 0){if(settlement.kind==="PARTIAL"&&verdict==="APPROVE")return rejected(state2,"partial_coverage_cannot_approve",`a partial review can never emit ${verdict}`);if(settlement.kind==="NO_COVERAGE"&&verdict!=="INCOMPLETE")return rejected(state2,"no_coverage_requires_incomplete",`a zero-coverage review must report INCOMPLETE, not ${verdict}`)}return applied(state2)}case"critic_result_recorded":{let settledFindingIds=new Set(event.criticSettledReceipts.filter((receipt)=>receipt.status==="UPHELD"||receipt.status==="DOWNGRADED"||receipt.status==="DISPROVED").map((receipt)=>receipt.findingId)),unfulfilled=event.criticRequiredFindingIds.filter((id)=>!settledFindingIds.has(id));if(unfulfilled.length>0)return rejected(state2,"critic_required_unfulfilled",`critic confirmation missing for finding(s): ${unfulfilled.join(", ")}`);return applied(state2)}case"armed_recovery_requested":{let reason=bindingRejection(state2,event);if(reason)return rejected(state2,"stale_foreign_authorization",reason.detail);let cancellations={...state2.prReviewDimensionCancellations??{}};for(let dimension of event.dimensionsToCancel)cancellations[dimension]={reason:event.reason,cancelledAt:event.nowIso,source:"armed_recovery"};return applied({...state2,prReviewDimensionCancellations:cancellations},[{kind:"persist_state"}])}default:{let exhausted=event;return rejected(state2,"unknown_event",`unknown PR-review event discriminant: ${event.type??"(none)"}`)}}}function bindingRejection(state2,event){let binding=event.binding;if(binding.sessionID!==state2.sessionID)return{detail:`authorization session ${binding.sessionID} is foreign to the active workflow session`};if(binding.workflowInstanceId!==void 0&&state2.workflowInstanceId!==void 0&&binding.workflowInstanceId!==state2.workflowInstanceId)return{detail:"authorization belongs to a different workflow instance"};if(!state2.prHeadSha||binding.prHeadSha!==state2.prHeadSha)return{detail:`authorization head ${binding.prHeadSha} does not match the bound head`};if(binding.generation!==currentGeneration(state2))return{detail:`authorization generation ${binding.generation} is stale (active: ${currentGeneration(state2)})`};return null}var init_reducer=__esm(()=>{init_circuit()});function classifyLaneLivenessCondition(input){if(input.recordStatus==="error")return"completed_failure";let sessionLiveOrUnknown=input.sessionStatusType===void 0||input.sessionStatusType==="busy"||input.sessionStatusType==="retry";if(input.waitBudgetExpired&&sessionLiveOrUnknown)return"observer_deadline";if(input.sessionStatusType==="retry")return"provider_retry_in_flight";if(input.exceededEffectiveHorizon)return"execution_deadline";return"idle_failed_child"}function resolveEffectivePrLaneHorizonMs(watchdog,backgroundPendingTimeoutMs){let watchdogOwnsHorizon=watchdog?.enabled===!0&&(watchdog.timeout_ms??0)>0,horizonMs=watchdogOwnsHorizon?watchdog?.timeout_ms:DEFAULT_STALE_DELEGATION_TIMEOUT_MS;return{horizonMs,source:watchdogOwnsHorizon?"watchdog-timeout":"reachability-floor",conflictDisclosed:backgroundPendingTimeoutMs!==void 0&&backgroundPendingTimeoutMs>0&&backgroundPendingTimeoutMs!==horizonMs}}function laneLivenessWatchdogFeatures(watchdog){let enabled=watchdog?.enabled===!0;return{deadlineActive:enabled&&(watchdog?.timeout_ms??0)>0,stallActive:enabled&&(watchdog?.stall_threshold_ms??0)>0&&(watchdog?.stall_min_steps??0)>0&&(watchdog?.stall_token_threshold??0)>0}}var LANE_LIVENESS_WATCHDOG_DEFAULTS,MAX_LANE_LIVENESS_DISCLOSED_IDS=10,ZERO_LANE_ACTIVITY,defaultReadLaneActivity=()=>ZERO_LANE_ACTIVITY;var init_lane_liveness_watchdog=__esm(()=>{init_pending_delegations();init_schema();LANE_LIVENESS_WATCHDOG_DEFAULTS=LaneLivenessWatchdogConfigSchema.parse({});ZERO_LANE_ACTIVITY={stepsObserved:0,estimatedTokens:0}});var exports_pr_workflow_gate={};__export(exports_pr_workflow_gate,{writePrWorkflowAtomicJson:()=>writePrWorkflowAtomicJson,withPrWorkflowCheckoutPreparationLock:()=>withPrWorkflowCheckoutPreparationLock,withPrWorkflowCheckoutMutationLock:()=>withPrWorkflowCheckoutMutationLock,withInactivePrWorkflowCheckoutRestoreLock:()=>withInactivePrWorkflowCheckoutRestoreLock,validatePrWorkflowTransportRecovery:()=>validatePrWorkflowTransportRecovery,validatePrReviewDiscoveryLaneCompletion:()=>validatePrReviewDiscoveryLaneCompletion2,validatePrFeedbackScopeBinding:()=>validatePrFeedbackScopeBinding,transitionPrReviewToFeedback:()=>transitionPrReviewToFeedback,terminalizePrWorkflowGateForSession:()=>terminalizePrWorkflowGateForSession2,submitPrReviewResult:()=>submitPrReviewResult,settlePresumedStalePrWorkflowLanes:()=>settlePresumedStalePrWorkflowLanes,rollbackPrReviewPartialBaseCoverageAdmission:()=>rollbackPrReviewPartialBaseCoverageAdmission,rollbackPrReviewBaseAdmissionIfUnlaunched:()=>rollbackPrReviewBaseAdmissionIfUnlaunched,resolvePrReviewWriterRunId:()=>resolvePrReviewWriterRunId,resolvePrFeedbackScopeDeclaration:()=>resolvePrFeedbackScopeDeclaration,reserveActivePrReviewReentryAuthorization:()=>reserveActivePrReviewReentryAuthorization,recoverArmedPrWorkflow:()=>recoverArmedPrWorkflow,recordPrReviewValidationBatch:()=>recordPrReviewValidationBatch,recordPrReviewSubmitRejection:()=>recordPrReviewSubmitRejection,recordPrFeedbackStageA:()=>recordPrFeedbackStageA,recordPrFeedbackPushAttemptResult:()=>recordPrFeedbackPushAttemptResult,recordPrFeedbackGateBatch:()=>recordPrFeedbackGateBatch,rebindPrFeedbackHead:()=>rebindPrFeedbackHead,readPrWorkflowGateStateForRecovery:()=>readPrWorkflowGateStateForRecovery,readPrWorkflowGateState:()=>readPrWorkflowGateState,readPrReviewTerminalCoverageForReport:()=>readPrReviewTerminalCoverageForReport,readPrReviewReentryBindingContext:()=>readPrReviewReentryBindingContext,readPrReviewFinalFindingPolicyForReport:()=>readPrReviewFinalFindingPolicyForReport,readAuthoritativePrReviewCriticVerdicts:()=>readAuthoritativePrReviewCriticVerdicts,readAuthoritativePrReviewCriticSettlements:()=>readAuthoritativePrReviewCriticSettlements,prWorkflowSessionFileStem:()=>prWorkflowSessionFileStem,prReviewDiscoveryArtifactCoversLane:()=>prReviewDiscoveryArtifactCoversLane,normalizePrWorkflowShellCommand:()=>normalizePrWorkflowShellCommand,normalizePrReviewPartialBaseCoverageRecord:()=>normalizePrReviewPartialBaseCoverageRecord,markPrReviewTriggerEvaluationComplete:()=>markPrReviewTriggerEvaluationComplete,markPrReviewHandoffComplete:()=>markPrReviewHandoffComplete,markPrReviewArtifactBoundary:()=>markPrReviewArtifactBoundary,latestPrReviewSubmitRejectionMessage:()=>latestPrReviewSubmitRejectionMessage,invalidatePrFeedbackPublication:()=>invalidatePrFeedbackPublication,hasActivePrReviewReentryAuthorization:()=>hasActivePrReviewReentryAuthorization,formatPrReviewLaneValidationFailure:()=>formatPrReviewLaneValidationFailure,findDanglingLivePublicationGeneration:()=>findDanglingLivePublicationGeneration,ensurePrWorkflowSafeParentDirectory:()=>ensurePrWorkflowSafeParentDirectory,enforcePrWorkflowToolBefore:()=>enforcePrWorkflowToolBefore,enforcePrWorkflowDispatchLanesAsync:()=>enforcePrWorkflowDispatchLanesAsync,enforcePrReviewBaseDimensions:()=>enforcePrReviewBaseDimensions,enforcePrFeedbackVerificationOwnership:()=>enforcePrFeedbackVerificationOwnership,describePrWorkflowRevisionDigestFailure:()=>describePrWorkflowRevisionDigestFailure,describePrWorkflowPublicationSection:()=>describePrWorkflowPublicationSection,declarePrFeedbackScope:()=>declarePrFeedbackScope,declarePrFeedbackInventory:()=>declarePrFeedbackInventory,consumePrFeedbackScopeDeclaration:()=>consumePrFeedbackScopeDeclaration,computePrReviewDepthTier:()=>computePrReviewDepthTier,completePrWorkflow:()=>completePrWorkflow,collectPrWorkflowPendingLaneLiveness:()=>collectPrWorkflowPendingLaneLiveness,clearPrWorkflowGateState:()=>clearPrWorkflowGateState,cancelPrFeedbackPublication:()=>cancelPrFeedbackPublication,bindPrWorkflowHead:()=>bindPrWorkflowHead,bindPrReviewTriggerLedger:()=>bindPrReviewTriggerLedger,bindPrReviewBase:()=>bindPrReviewBase,assertPrReviewValidationSettled:()=>assertPrReviewValidationSettled,assertPrReviewCleanCheckout:()=>assertPrReviewCleanCheckout,assertPrReviewBaseCoverageSettled:()=>assertPrReviewBaseCoverageSettled2,assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts:()=>assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts,assertPrReviewArtifactBoundary:()=>assertPrReviewArtifactBoundary,assertPrFeedbackVerificationSettled:()=>assertPrFeedbackVerificationSettled,assertPrFeedbackReadyToPublish:()=>assertPrFeedbackReadyToPublish,assertPrFeedbackGatePhaseSettled:()=>assertPrFeedbackGatePhaseSettled,assertCurrentCheckoutHead:()=>assertCurrentCheckoutHead,allowedPrReviewReportVerdicts:()=>allowedPrReviewReportVerdicts,admitPrReviewPartialBaseCoverage:()=>admitPrReviewPartialBaseCoverage2,activatePrWorkflow:()=>activatePrWorkflow,abortPrWorkflow:()=>abortPrWorkflow,_test_exports:()=>_test_exports2,PrWorkflowCheckoutMutationTimeoutError:()=>PrWorkflowCheckoutMutationTimeoutError,PrReviewResilienceRetryExhaustedError:()=>PrReviewResilienceRetryExhaustedError,PrReviewResilienceCircuitOpenError:()=>PrReviewResilienceCircuitOpenError,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON:()=>PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR:()=>PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_REQUIRED_MICRO_LANE_IDS:()=>PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_REPORT_VERDICTS:()=>PR_REVIEW_REPORT_VERDICTS,PR_REVIEW_MICRO_LANE_FLOORS:()=>PR_REVIEW_MICRO_LANE_FLOORS,PR_REVIEW_DEPTH_TIER_THRESHOLDS:()=>PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS:()=>PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_BASE_DIMENSION_IDS:()=>PR_REVIEW_BASE_DIMENSION_IDS,MAX_SALVAGED_SCHEMA_ERROR_CHARS:()=>MAX_SALVAGED_SCHEMA_ERROR_CHARS,MAX_PR_REVIEW_SUBMIT_REJECTIONS:()=>MAX_PR_REVIEW_SUBMIT_REJECTIONS,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS:()=>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS});import{createHash as createHash53,randomUUID as randomUUID17}from"node:crypto";import{readFileSync as readFileSync42,statSync as statSync39}from"node:fs";import*as fsp8 from"node:fs/promises";import*as path106 from"node:path";function readPrWorkflowGateStateFromDisk3(directory,sessionID){return readPrWorkflowGateStateFromDisk(directory,sessionID)}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(state2){let evidence2=JSON.stringify({operations:state2.evidence.operations,unmerged_codes:state2.evidence.unmergedCodes,paths:state2.evidence.paths,paths_truncated:state2.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state2.code} retryable=false required_action=${state2.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state2){if(state2.kind!=="recovery-required"&&state2.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state2.code,retryable:!1,requiredAction:state2.requiredAction,evidence:state2.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_exports2.classifyPrWorkflowGitStateAsync(directory):null;return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let existing=await readPrWorkflowGateStateFromDisk3(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_exports2.classifyPrWorkflowGitStateAsync(directory,{ignoredPaths:[path106.join(".swarm",workflowCheckoutMutationLockRelativePath()),path106.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:randomUUID17(),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),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state2)rememberState(directory,state2);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state2}function isLivenessTerminalLaneRecord(record3){if(record3.status!=="cancelled"&&record3.status!=="stale"&&record3.status!=="error")return!1;return record3.terminalResult?.result.workflowLaneFailureClass==="liveness"||record3.result?.workflowLaneFailureClass==="liveness"}async function recordPrReviewSubmitRejection(directory,childSessionId,message){try{let child=childSessionId.trim();if(!child)return;let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return;let record3=childRead.records.find((candidate)=>candidate.subagentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")),parentSessionId=record3?.parentSessionId?.trim();if(!parentSessionId)return;let existing=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!existing||existing.mode!=="PR_REVIEW")return;let laneId=record3?.laneId?.trim(),bounded=redactSecrets(message.replace(PUBLICATION_URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@")).slice(0,300);await withSessionStateMutation(directory,parentSessionId,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!locked||locked.mode!=="PR_REVIEW")return;let prior=locked.prReviewSubmitRejections??[];if(prior.filter((entry)=>entry.childSessionId===child).at(-1)?.message===bounded)return;let journal=[...prior,{childSessionId:child,...laneId?{laneId}:{},at:Date.now(),message:bounded}].slice(-MAX_PR_REVIEW_SUBMIT_REJECTIONS);await writeStateWhileLocked(directory,{...locked,prReviewSubmitRejections:journal,updatedAt:isoNow()})})}catch{}}function latestPrReviewSubmitRejectionMessage(state2,childSessionId){let journal=state2.prReviewSubmitRejections;if(!journal?.length)return;for(let index=journal.length-1;index>=0;index--)if(journal[index]?.childSessionId===childSessionId)return journal[index]?.message;return}async function submitPrReviewResultCore(directory,childSessionId,input){let child=childSessionId.trim(),parsedResult=PrReviewLaneResultEnvelopeSchema.safeParse(input.result);if(!child||!parsedResult.success)return{status:"rejected",reason:"invalid child session or result envelope"};let childRead=readDelegationsDetailed(directory);if(childRead.status==="uncertain")return{status:"rejected",reason:`delegation store unreadable after ${childRead.attempts} attempts; child lookup uncertain (${childRead.reason})`};let preliminary=childRead.records.filter((record4)=>record4.subagentSessionId===child&&record4.correlationId===child&&(record4.mode==="swarm-pr-review:base"||record4.mode==="swarm-pr-review:micro")),repairRecord=null;if(preliminary.length!==1){let repairCandidates=childRead.records.filter((candidate)=>candidate.parentSessionId===child&&(candidate.mode==="swarm-pr-review:base"||candidate.mode==="swarm-pr-review:micro")&&(input.batchId===void 0||input.batchId===candidate.batchId)&&(input.laneId===void 0||input.laneId===candidate.laneId)&&isLivenessTerminalLaneRecord(candidate));if(repairCandidates.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};if(repairRecord=repairCandidates[0],parsedResult.data.outcome!=="INCOMPLETE")return{status:"rejected",reason:"architect-parent repair may only record an unresolved-terminal (INCOMPLETE) outcome"}}let parentSessionId=(repairRecord??preliminary[0]).parentSessionId,record3=repairRecord??preliminary[0],childOfRecord=record3.subagentSessionId;if(!record3.batchId||!record3.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record3.batchId||input.laneId!==void 0&&input.laneId!==record3.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record3;return withSessionStateMutation(directory,parentSessionId,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state2||state2.mode!=="PR_REVIEW"||!state2.workflowInstanceId||!state2.prHeadSha||!state2.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state2)).revisionDigest!==input.revisionDigest)return{status:"rejected",reason:"stale dispatch revision digest"};let dispatchWorkflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),dispatchWorkflowRevision=record3.workflowGeneration;if(!dispatchWorkflowInstanceId||dispatchWorkflowRevision===void 0)return{status:"rejected",reason:"delegation workflow binding provenance is missing"};if(dispatchWorkflowInstanceId!==state2.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};if(repairRecord&&dispatchWorkflowRevision!==state2.revision)return{status:"rejected",reason:`superseded workflow generation binding (delegation generation ${dispatchWorkflowRevision}, active generation ${state2.revision})`};if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record3.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:[];if(!record3.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record3.result?.prReviewResultReceipt?.semanticEnvelopeDigest,submission=reducePrReviewEvent(state2,{type:"lane_structured_result_submitted",batchId,laneId,generation:state2.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{},...repairRecord?{submittedBy:"workflow_parent"}:{}});if(submission.status==="rejected")return{status:"rejected",reason:submission.rejection.code==="duplicate_conflicting_result"?"a different bound receipt is already recorded":`structured result submission rejected: ${submission.rejection.code}`};let published=await publishPrReviewResultReceipt(directory,{parentSessionId,childSessionId:childOfRecord,batchId,laneId,expectedWorkflowInstanceId:state2.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state2.prReviewBaseSha,...repairRecord?{parentRepair:!0}:{},receipt:{schemaVersion:1,mode:record3.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record3.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record3.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record3.status}:{}}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function submitPrReviewResult(directory,childSessionId,input){let outcome=await submitPrReviewResultCore(directory,childSessionId,input);if(outcome.status==="rejected")await recordPrReviewSubmitRejection(directory,childSessionId,outcome.reason);return outcome}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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(state2.prHeadSha)throw Error(`BLOCKED: ${state2.mode} checkout preparation is allowed only before the PR head is bound`);return action2(state2,{markRecoveryRequired:async(gitState)=>{let nextState={...state2,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state2,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action2){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await readPrWorkflowGateStateFromDisk3(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),action2()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp8.opendir(gateDirectory)}catch(error93){if(error93.code==="ENOENT")return;throw error93}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 statePath2=validateSwarmPath(directory,path106.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path106.basename(workflowGateStateRelativePath(state2.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");let boundedEntryName=entry.name.length<=MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS?entry.name:`${entry.name.slice(0,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS-1)}…`;throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state2.sessionID}" has an active ${state2.mode} workflow (state entry "${boundedEntryName}"). For the owning session, run \`/swarm abort-pr-workflow ${state2.mode} <reason...>\` to recover the stuck gate.`)}}catch(error93){scanError=error93}finally{try{await handle.close()}catch(error93){if(error93.code!=="ERR_DIR_CLOSED")closeError=error93}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,options={}){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{if(expectedRevision!==void 0){let current=options.allowSalvagedRead?(await readPrWorkflowGateStateForRecovery(directory,normalizedSessionID))?.state??null:await readPrWorkflowGateStateFromDisk3(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")}await deleteStateWhileLocked(directory,normalizedSessionID,{expectedStateRevision:expectedRevision,allowSalvagedRead:options.allowSalvagedRead})})}async function terminalizePrWorkflowGateForSession2(directory,sessionID){return terminalizePrWorkflowGateForSession(directory,sessionID)}function isLiveSessionStatusType(type){return LIVE_SESSION_STATUS_TYPES.has(type)}async function probePrWorkflowLaneSessionStatusTypes(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),statusOp=session?.status;if(!session||typeof statusOp!=="function")return{statuses:new Map,degradedReason:"probe-unavailable"};let timeoutError=Error("PR workflow lane liveness probe exceeded its deadline"),response;try{response=await withTimeout((async()=>statusOp.call(session,{query:{directory}}))(),timeoutMs??_test_exports2.laneLivenessProbeTimeoutMs,timeoutError)}catch(error93){return{statuses:new Map,degradedReason:error93===timeoutError?"probe-timeout":"probe-error"}}try{if(response?.error)return{statuses:new Map,degradedReason:"probe-error"};let data=response?.data;if(data===null||data===void 0)return{statuses:new Map,degradedReason:"probe-no-data"};let statuses=new Map;for(let record3 of records){let subagentSessionId=record3.subagentSessionId;if(!subagentSessionId)continue;let type=data[subagentSessionId]?.type;if(typeof type==="string")statuses.set(subagentSessionId,type)}return{statuses}}catch{return{statuses:new Map,degradedReason:"probe-error"}}}async function probeAlivePrWorkflowLaneSessions(directory,records){let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,records);if(probe2.degradedReason)return{alive:new Set,degradedReason:probe2.degradedReason};let alive=new Set;for(let[sessionId,type]of probe2.statuses)if(isLiveSessionStatusType(type))alive.add(sessionId);return{alive}}async function collectPrWorkflowPendingLaneLiveness(directory,records,options={}){let now=0,pastThreshold=[],degraded=(record3,reason)=>({laneId:record3.laneId??record3.correlationId,pendingMs:Math.max(0,now-record3.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record3)=>(record3.status==="pending"||record3.status==="running"||record3.status==="ingesting")&&now-record3.updatedAt>threshold),pastThreshold.length===0)return[];let budgetMs=Math.max(0,Math.min(_test_exports2.laneLivenessProbeTimeoutMs,options.probeBudgetMs??Number.POSITIVE_INFINITY));if(budgetMs<=0)return pastThreshold.map((record3)=>degraded(record3,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record3 of pastThreshold){let pendingMs=now-record3.updatedAt,laneId=record3.laneId??record3.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record3.subagentSessionId,type=subagentSessionId?probe2.statuses.get(subagentSessionId):void 0;if(type===void 0){advisories.push({laneId,pendingMs,hostStatus:subagentSessionId?"absent":"unknown",stalledSuspect:!0});continue}advisories.push({laneId,pendingMs,hostStatus:type,stalledSuspect:!isLiveSessionStatusType(type)})}return advisories}catch{return pastThreshold.map((record3)=>degraded(record3,"advisory-unavailable"))}}function describePrWorkflowLaneProbe(settlement){let parts=[];if(settlement.probedAliveLaneIds?.length)parts.push(`liveness probe reports still running: ${settlement.probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`);if(settlement.probeDegradedReason)parts.push(`liveness probe degraded (${settlement.probeDegradedReason})`);return parts.length>0?` (${parts.join("; ")})`:""}function prWorkflowLaneLabel(record3){return record3.laneId??record3.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record3,sessionID){return record3.parentSessionId===sessionID&&record3.mode?.startsWith("swarm-pr-")===!0&&(record3.status==="pending"||record3.status==="running")}async function abortLaneSessionForWatchdog(record3){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record3.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record3.subagentSessionId}}),_test_exports2.laneLivenessProbeTimeoutMs,Error("lane-liveness watchdog abort exceeded its deadline")),!0}catch{return!1}}function lastWatchdogEscalationsByLaneLabel(directory,sessionID){let escalations=new Map,activityObservations=new Map,deadlineLabels=new Set,text="";try{text=readCoreEvents(directory).text}catch{return{escalations,activityObservations,deadlineLabels}}for(let line of text.split(`
|
|
1306
1306
|
`)){let trimmed=line.trim();if(!trimmed||!trimmed.includes("pr_workflow_lane_watchdog"))continue;let event;try{event=JSON.parse(trimmed)}catch{continue}if(event.type!=="pr_workflow_lane_watchdog")continue;if(sessionID!==void 0&&event.sessionID!==sessionID)continue;let isEscalation=event.escalated===!0,isActivityObservation=!isEscalation&&event.activityObserved===!0,isDeadlineEvent=!isEscalation&&!isActivityObservation&&event.condition==="execution_deadline";if(!isEscalation&&!isActivityObservation&&!isDeadlineEvent)continue;let timestamp=Date.parse(`${event.timestamp}`);if(!Number.isFinite(timestamp))continue;let laneIds=event.laneIds;if(!Array.isArray(laneIds))continue;let target=isEscalation?escalations:activityObservations;for(let label of laneIds){if(typeof label!=="string")continue;if(isDeadlineEvent){deadlineLabels.add(label);continue}let prior=target.get(label);if(prior===void 0||timestamp>prior)target.set(label,timestamp)}}return{escalations,activityObservations,deadlineLabels}}function appendWatchdogActivityObservation(directory,sessionID,labels,horizon,condition){try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition,laneIds:labels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!1,activityObserved:!0,disclosure:`${labels.length} lane(s) progressed (activity observed since the last escalation); stall escalation baseline reset`})}catch{}}async function evaluateLaneLivenessWatchdogEscalation(args2){let{directory,sessionID,lanes,sessionTypes,watchdog,horizon}=args2,candidates=lanes.filter((record3)=>{if(!record3.subagentSessionId)return!1;let type=sessionTypes.get(record3.subagentSessionId);return type==="busy"||type==="retry"});if(candidates.length===0)return;let lastEscalations=lastWatchdogEscalationsByLaneLabel(directory,sessionID),escalated=[],progressed=[],firstEscalatedSteps=0,firstEscalatedTokens=0;for(let record3 of candidates){let activity=null;try{activity=await laneLivenessWatchdogSurface.readLaneActivity(directory,record3.subagentSessionId)}catch{activity=null}let steps=activity?.stepsObserved??0,tokens2=activity?.estimatedTokens??0;if(steps>=watchdog.stall_min_steps||tokens2>=watchdog.stall_token_threshold){progressed.push(record3);continue}let label=prWorkflowLaneLabel(record3),lastEscalation=lastEscalations.escalations.get(label);if(lastEscalation!==void 0){let lastActivity=activity?.lastActivityAtMs;if(!(lastActivity!==void 0&&lastActivity>=lastEscalation||(lastEscalations.activityObservations.get(label)??-1/0)>=lastEscalation))continue}if(escalated.length===0)firstEscalatedSteps=steps,firstEscalatedTokens=tokens2;escalated.push(record3)}if(progressed.length>0){let firstProgressed=progressed[0],firstProgressedType=firstProgressed.subagentSessionId?sessionTypes.get(firstProgressed.subagentSessionId):void 0;appendWatchdogActivityObservation(directory,sessionID,progressed.map(prWorkflowLaneLabel),horizon,firstProgressedType==="retry"?"provider_retry_in_flight":"idle_failed_child")}if(escalated.length===0)return;let first=escalated[0],condition=classifyLaneLivenessCondition({sessionStatusType:first.subagentSessionId?sessionTypes.get(first.subagentSessionId):void 0,recordStatus:first.status,waitBudgetExpired:!1,exceededEffectiveHorizon:Date.now()-first.updatedAt>horizon.horizonMs}),laneLabels=escalated.map(prWorkflowLaneLabel),disclosure=`${laneLabels.length} lane(s) stalled (fewer than ${watchdog.stall_min_steps} steps and fewer than ~${watchdog.stall_token_threshold} estimated tokens in the last ${watchdog.stall_threshold_ms}ms): inspect the lane transcript or abort via /swarm abort-pr-workflow (force): ${laneLabels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS).join(", ")}`;try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition,laneIds:laneLabels.slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!0,stall:{stepsObserved:firstEscalatedSteps,estimatedTokens:firstEscalatedTokens,stallThresholdMs:watchdog.stall_threshold_ms,stallMinSteps:watchdog.stall_min_steps,stallTokenThreshold:watchdog.stall_token_threshold},disclosure})}catch{}}async function settlePresumedStalePrWorkflowLanes(directory,sessionID,options){let watchdog=options?.laneLivenessWatchdog,{deadlineActive,stallActive}=laneLivenessWatchdogFeatures(watchdog),watchdogWork=deadlineActive||stallActive,horizon=resolveEffectivePrLaneHorizonMs(watchdog,options?.backgroundPendingTimeoutMs),horizonConflictNote=horizon.conflictDisclosed?horizon.source==="watchdog-timeout"?`lane_liveness_watchdog.timeout_ms (${horizon.horizonMs}ms) governs the PR-lane settlement horizon; hooks.background_pending_timeout_minutes was also set and disagrees — it was not applied (one effective horizon)`:`PR-lane settlement uses the ${Math.round(horizon.horizonMs/60000)}min reachability floor; hooks.background_pending_timeout_minutes disagrees with it and does not change this horizon`:void 0,now=Date.now(),open7=[],presumedStale=[],laneRead=readDelegationsDetailed(directory);if(laneRead.status==="uncertain")return{openLaneIds:[],openLanes:0,freshOpenLanes:0,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{},uncertainty:{reason:laneRead.reason,attempts:laneRead.attempts}};for(let record3 of laneRead.records){if(!isOpenPrWorkflowLane(record3,sessionID))continue;if(now-record3.updatedAt>horizon.horizonMs)presumedStale.push(record3);else open7.push(record3)}if(watchdogWork&&(open7.length>0||presumedStale.length>0))laneLivenessWatchdogSurface.evaluations+=1;if(presumedStale.length===0){if(watchdogWork&&stallActive&&open7.length>0){let statuses=new Map;try{let probe3=await _test_exports2.probeLaneSessionStatusTypesAsync(directory,open7);if(statuses=probe3.statuses,!probe3.degradedReason)laneLivenessWatchdogSurface.hostStatusCalls+=1}catch{}if(statuses.size>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:open7,sessionTypes:statuses,watchdog,horizon})}return{openLaneIds:open7.map(prWorkflowLaneLabel),openLanes:open7.length,freshOpenLanes:open7.length,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{}}}let probe2,sessionTypes=new Map;if(watchdogWork)try{let typesProbe=await _test_exports2.probeLaneSessionStatusTypesAsync(directory,stallActive?[...presumedStale,...open7]:presumedStale);if(sessionTypes=typesProbe.statuses,!typesProbe.degradedReason)laneLivenessWatchdogSurface.hostStatusCalls+=1;let alive=new Set;for(let[sessionId,type]of typesProbe.statuses)if(isLiveSessionStatusType(type))alive.add(sessionId);probe2=typesProbe.degradedReason?{alive:new Set,degradedReason:typesProbe.degradedReason}:{alive}}catch{probe2={alive:new Set,degradedReason:"probe-error"}}else try{probe2=await _test_exports2.probeLaneLivenessAsync(directory,presumedStale)}catch{probe2={alive:new Set,degradedReason:"probe-error"}}let probeRetained=[],settled=[],deadlineLanes=[];for(let record3 of presumedStale){let type=record3.subagentSessionId?sessionTypes.get(record3.subagentSessionId):void 0;if(deadlineActive&&type!=="retry")deadlineLanes.push(record3),settled.push(record3);else if(record3.subagentSessionId&&probe2.alive.has(record3.subagentSessionId))probeRetained.push(record3);else if(deadlineActive)deadlineLanes.push(record3),settled.push(record3);else settled.push(record3)}let probedAliveLaneIds=probeRetained.map(prWorkflowLaneLabel),openLaneIds=[...open7.map(prWorkflowLaneLabel),...probedAliveLaneIds],retentionDisclosure=probeRetained.length>0?`${probeRetained.length} lane(s) past the horizon retained: liveness probe reports still running: ${probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`:void 0,retentionFields={...probedAliveLaneIds.length>0?{probedAliveLaneIds,probeRetainedCorrelationIds:probeRetained.map((record3)=>record3.correlationId)}:{},...probe2.degradedReason?{probeDegradedReason:probe2.degradedReason}:{}};if(settled.length===0){if(watchdogWork&&stallActive&&probeRetained.length>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:probeRetained,sessionTypes,watchdog,horizon});return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open7.length,presumedStaleLaneIds:[],...horizonConflictNote?{horizonConflictNote}:{},...retentionFields,disclosure:retentionDisclosure}}if(deadlineActive){let priorDeadlineLabels=lastWatchdogEscalationsByLaneLabel(directory,sessionID).deadlineLabels,abortAttempted=!1;for(let record3 of deadlineLanes){if((record3.subagentSessionId?sessionTypes.get(record3.subagentSessionId):void 0)!=="busy"||!record3.subagentSessionId)continue;if(priorDeadlineLabels.has(prWorkflowLaneLabel(record3)))continue;if(abortAttempted=!0,await abortLaneSessionForWatchdog(record3))laneLivenessWatchdogSurface.hostAbortCalls+=1}if(deadlineLanes.length>0)try{appendCoreEventSync(directory,{type:"pr_workflow_lane_watchdog",timestamp:isoNow(),sessionID,condition:"execution_deadline",laneIds:deadlineLanes.map(prWorkflowLaneLabel).slice(0,MAX_LANE_LIVENESS_DISCLOSED_IDS),effectiveHorizonMs:horizon.horizonMs,horizonSource:horizon.source,escalated:!1,disclosure:`${deadlineLanes.length} lane(s) exceeded the ${horizon.horizonMs}ms execution deadline (${horizon.source}); `+(abortAttempted?"sessions aborted best-effort and settled ":"no session abort was attempted (the liveness probe could not confirm these sessions were running); lanes settled ")+"through the shared path with the real outcome: no output observed (no transcript activity recorded for these lanes)"})}catch{}}let presumedStaleLaneIds=settled.map(prWorkflowLaneLabel),disclosure=`${presumedStaleLaneIds.length} lane(s) stale >${Math.round(horizon.horizonMs/60000)}min, treated as settled: ${presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}`+(probe2.degradedReason?`; settled despite liveness probe failure (${probe2.degradedReason})`:"; liveness probe found no live session")+(retentionDisclosure?`; ${retentionDisclosure}`:"");try{await _test_exports2.sweepStaleDelegationsAsync(directory,horizon.horizonMs,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,excludeCorrelationIds:new Set(probeRetained.map((record3)=>record3.correlationId))})}catch{}try{appendCoreEventSync(directory,{type:"pr_workflow_lanes_presumed_stale",timestamp:isoNow(),sessionID,presumedStaleLanes:presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),staleTimeoutMs:horizon.horizonMs,probeStatus:probe2.degradedReason??"ok",probedAliveLanes:probedAliveLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),disclosure})}catch{}if(watchdogWork&&stallActive&&!(deadlineActive&&deadlineLanes.length>0)){let stallCandidates=[...open7,...probeRetained];if(stallCandidates.length>0&&sessionTypes.size>0)await evaluateLaneLivenessWatchdogEscalation({directory,sessionID,lanes:stallCandidates,sessionTypes,watchdog,horizon});else if(stallCandidates.length>0);}return{openLaneIds,openLanes:openLaneIds.length,freshOpenLanes:open7.length,presumedStaleLaneIds,...horizonConflictNote?{horizonConflictNote}:{},...retentionFields,disclosure}}async function finalizeOverriddenProbeRetainedLanes(directory,sessionID,correlationIds,horizonMs=PR_WORKFLOW_STALE_LANE_TIMEOUT_MS){try{await _test_exports2.sweepStaleDelegationsAsync(directory,horizonMs,{statuses:PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,includeCorrelationIds:new Set(correlationIds)})}catch{}let targeted=new Set(correlationIds),outcome={sessionOpenLaneIds:[],finalizedLaneIds:[],sparedLaneDescriptions:[]},finalizeRead=readDelegationsDetailed(directory);if(finalizeRead.status==="uncertain")return{...outcome,delegationReadUncertain:`${finalizeRead.reason} (after ${finalizeRead.attempts} attempts)`};for(let record3 of finalizeRead.records){if(isOpenPrWorkflowLane(record3,sessionID))outcome.sessionOpenLaneIds.push(record3.correlationId);if(!targeted.has(record3.correlationId))continue;if(record3.status==="stale")outcome.finalizedLaneIds.push(record3.correlationId);else if(record3.status!=="pending"&&record3.status!=="running")outcome.sparedLaneDescriptions.push(`${record3.correlationId} (${record3.status})`)}return outcome}async function abortPrWorkflow(directory,sessionID,options={kind:"recovery",reason:""}){let recovery=await readPrWorkflowGateStateForRecovery(directory,sessionID);if(!recovery){if(options.cancelPublication){if(!options.reason.trim())throw Error("BLOCKED: cancel_publication requires a non-empty reason; the cancellation reason is part of the durable audit trail");let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(!dangling)throw noActiveGateError(sessionID);return appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:normalizeSessionID(sessionID),generation:dangling.generation,reason:options.reason.trim(),stateFileAbsent:!0,observedRemoteHead:null}),{mode:"PR_FEEDBACK",observedRemoteHead:null,openLanes:0,stateSalvaged:!1,stateSalvageDisclosure:"The gate state file was already absent; the live publication generation in the audit trail was recorded as cancelled_without_publication (event-only terminal)."}}throw noActiveGateError(sessionID)}let state2=recovery.state,cancelRevision=null,cancellationObservedRemoteHead;if(options.expectedMode&&state2.mode!==options.expectedMode)throw wrongModeError(state2,options.expectedMode);if(options.cancelPublication){if(options.kind==="force")throw Error('BLOCKED: cancel_publication cannot be combined with kind "force"; use kind "cancel-publication" with a reason');if(options.kind!=="cancel-publication")throw Error('BLOCKED: cancel_publication requires kind "cancel-publication"; do not combine it with kind "recovery" or "force"');if(!options.reason.trim())throw Error("BLOCKED: cancel_publication requires a non-empty reason; the cancellation reason is part of the durable audit trail");let activeState=state2.prFeedbackPublication?.active?.state;if(activeState==="published")throw Error("BLOCKED: PR_FEEDBACK publication is already marked published; use complete_pr_workflow so the actual remote branch is re-verified before the gate clears");if(state2.mode!=="PR_FEEDBACK"||!state2.prFeedbackReadyToPublish&&!recovery.armedShapeUnreadable&&activeState!=="armed"&&activeState!=="push_in_flight"&&activeState!=="invalidated"&&activeState!=="cancelled_without_publication")throw Error("BLOCKED: cancel_publication applies only to a PR_FEEDBACK workflow with a publication generation (armed, push_in_flight, or invalidated)");let cancellation=await cancelPrFeedbackPublication(directory,sessionID,options.reason.trim());cancelRevision=cancellation.revision,cancellationObservedRemoteHead=cancellation.observedRemoteHead}if(state2.prFeedbackPublication?.active?.state==="published")throw Error("BLOCKED: PR_FEEDBACK publication is already marked published; use complete_pr_workflow so the actual remote branch is re-verified before the gate clears");if((state2.prFeedbackReadyToPublish||recovery.armedShapeUnreadable)&&!options.cancelPublication)throw Error(`BLOCKED: ${state2.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting, or use the audited cancellation (abort_pr_workflow with cancel_publication and a reason).`+(recovery.armedShapeUnreadable?" The publication-arming record is itself unreadable, so it is treated as armed (fail-closed).":""));let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options.laneLiveness),probeRetainedLanes=laneSettlement.probedAliveLaneIds??[],overridesProbeRetention=options.kind==="force"&&laneSettlement.freshOpenLanes===0&&probeRetainedLanes.length>0;if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${state2.mode} abort refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store (see the settlement disclosure) or retry once it is readable before aborting.`);if(laneSettlement.openLanes>0&&!overridesProbeRetention){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: ${state2.mode} abort refused while ${laneSettlement.openLanes} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before aborting.`+describePrWorkflowLaneProbe(laneSettlement))}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: ${state2.mode} abort requires a non-empty reason (recorded to the audit trail).`);let overrideTargetedLaneIds=overridesProbeRetention?laneSettlement.probeRetainedCorrelationIds??[]:[],probeRetentionOverrideDecision=overridesProbeRetention?`force abort overrode ${probeRetainedLanes.length} lane(s) past the staleness horizon that the liveness probe reported as still running: ${probeRetainedLanes.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}. Their sessions were NOT stopped and their output was NOT collected.`:void 0,abortEvent={type:"pr_workflow_aborted",timestamp:isoNow(),sessionID:state2.sessionID,mode:state2.mode,kind:options.kind,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},...state2.checkoutRecovery?{hadTerminalRecovery:!0}:{},openLanes:laneSettlement.openLanes,...laneSettlement.presumedStaleLaneIds.length>0?{presumedStaleLanes:laneSettlement.presumedStaleLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),presumedStaleDisclosure:laneSettlement.disclosure}:{},...probeRetainedLanes.length>0?{probeRetainedLanes:probeRetainedLanes.slice(0,MAX_DISCLOSED_LANE_IDS)}:{},...probeRetentionOverrideDecision?{probeRetentionOverrideDisclosure:probeRetentionOverrideDecision}:{},...overridesProbeRetention?{probeRetentionOverrideLanes:overrideTargetedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS)}:{},...laneSettlement.probeDegradedReason?{probeStatus:laneSettlement.probeDegradedReason}:{},...recovery.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:recovery.disclosure,...recovery.revisionSalvageable?{}:{casEscapeDisclosure:CAS_ESCAPE_DISCLOSURE}}:{},reason:sanitizedReason};try{appendCoreEventSync(directory,abortEvent)}catch{}let casEscape=recovery.salvaged&&!recovery.revisionSalvageable;await _test_exports2.beforeAbortClear?.();try{await clearPrWorkflowGateState(directory,sessionID,casEscape?void 0:cancelRevision??state2.revision,{allowSalvagedRead:recovery.salvaged})}catch(error93){try{appendCoreEventSync(directory,{type:"pr_workflow_abort_not_completed",timestamp:isoNow(),sessionID:state2.sessionID,mode:state2.mode,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},reason:sanitizedReason,...overridesProbeRetention?{probeRetentionOverrideLanes:overrideTargetedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS),probeRetentionOverrideFinalized:!1}:{},failure:(error93 instanceof Error?error93.message:String(error93)).slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2),disclosure:"RETRACTION: the pr_workflow_aborted record for this session did NOT complete — "+"the clear failed and the gate state may still be active. Revalidate the current session state before retrying the abort."+(overridesProbeRetention?" The probe-retention override finalized no record: it runs only after the clear succeeds, and this clear failed. Other lanes in the same settlement "+"batch may already have been finalized as presumed-stale, and a concurrent abort for this session may have finalized more — revalidate the lane records rather than assuming they are untouched.":"")})}catch{}throw error93}let overrideOutcome=overridesProbeRetention?await finalizeOverriddenProbeRetainedLanes(directory,state2.sessionID,overrideTargetedLaneIds,resolveEffectivePrLaneHorizonMs(options.laneLiveness?.laneLivenessWatchdog,options.laneLiveness?.backgroundPendingTimeoutMs).horizonMs):{sessionOpenLaneIds:[],finalizedLaneIds:[],sparedLaneDescriptions:[]},probeRetentionOverrideDisclosure=probeRetentionOverrideDecision?probeRetentionOverrideDecision+(overrideOutcome.finalizedLaneIds.length===0?"":` Their delegation records were finalized (correlationId: ${overrideOutcome.finalizedLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}); whatever those lanes still produce is no longer collectable.`)+(overrideOutcome.sparedLaneDescriptions.length===0?"":` ${overrideOutcome.sparedLaneDescriptions.length} of the overridden lane(s) were NOT finalized: the sweep left those records intact at the status they had already reached (${overrideOutcome.sparedLaneDescriptions.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}). This abort did not discard them — check collect_lane_results before assuming that work is gone.`)+(overrideOutcome.delegationReadUncertain!==void 0?` WARNING: the post-abort delegation-store re-read was unreadable (${overrideOutcome.delegationReadUncertain}); whether any PR workflow delegation record(s) for this session remain open is UNKNOWN — revalidate with pr_workflow_status before assuming a new PR workflow can start.`:overrideOutcome.sessionOpenLaneIds.length===0?" A new PR workflow can now be started for this session.":` WARNING: ${overrideOutcome.sessionOpenLaneIds.length} PR workflow delegation record(s) for this session are still open (correlationId: ${overrideOutcome.sessionOpenLaneIds.slice(0,MAX_DISCLOSED_LANE_IDS).join(", ")}) and will keep refusing PR workflow checkout preparation for this session until they settle.`):void 0;return{mode:state2.mode,...state2.prHeadSha?{prHeadSha:state2.prHeadSha}:{},...cancellationObservedRemoteHead!==void 0?{observedRemoteHead:cancellationObservedRemoteHead}:{},openLanes:laneSettlement.openLanes,...laneSettlement.presumedStaleLaneIds.length>0?{presumedStaleLanes:laneSettlement.presumedStaleLaneIds,presumedStaleDisclosure:laneSettlement.disclosure}:{},...probeRetainedLanes.length>0?{probeRetainedLanes}:{},...probeRetentionOverrideDisclosure?{probeRetentionOverrideDisclosure}:{},...laneSettlement.probeDegradedReason?{probeDegradedReason:laneSettlement.probeDegradedReason}:{},...recovery.salvaged?{stateSalvaged:!0,stateSalvageDisclosure:recovery.disclosure}:{},...casEscape?{casEscapeDisclosure:CAS_ESCAPE_DISCLOSURE}:{}}}async function recoverArmedPrWorkflow(directory,sessionID,request){let sanitizedReason=typeof request.reason==="string"&&request.reason.trim().length>0?request.reason.trim().slice(0,500):void 0;if(sanitizedReason===void 0)throw Error("BLOCKED: armed recovery requires a non-empty reason (recorded to the audit trail).");return withSessionStateMutation(directory,normalizeSessionID(sessionID),async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2)throw noActiveGateError(sessionID);if(request.expectedMode&&state2.mode!==request.expectedMode)throw wrongModeError(state2,request.expectedMode);let armed=state2.prFeedbackReadyToPublish;if(!armed)throw Error(`BLOCKED: ${state2.mode} is not armed for publication; armed recovery applies only to an active staged publication authorization (complete or abort normally instead).`);if(request.prHeadSha!==state2.prHeadSha)throw Error(`BLOCKED: armed recovery head mismatch: workflow is bound to "${state2.prHeadSha??"(none)"}", request declared "${request.prHeadSha}".`);if(state2.prReviewBaseSha===void 0!==(request.baseSha===void 0))throw Error(`BLOCKED: armed recovery base mismatch: ${state2.prReviewBaseSha===void 0?"the active workflow has no merge-base binding but the request declared one":"the active workflow is merge-base bound but the request omitted base_sha"}; fail closed.`);if(request.baseSha!==void 0&&state2.prReviewBaseSha!==void 0&&request.baseSha!==state2.prReviewBaseSha)throw Error(`BLOCKED: armed recovery base mismatch: workflow is merge-base bound to "${state2.prReviewBaseSha}", request declared "${request.baseSha}".`);if(request.revisionDigest!==armed.revisionDigest)throw Error("BLOCKED: armed recovery revision digest does not match the staged publication authorization; fail closed.");if(request.generation!==state2.revision)throw Error(`BLOCKED: armed recovery generation mismatch: current gate generation is ${state2.revision}, request declared ${request.generation}. Stale requests fail closed; re-read the workflow state and retry.`);if(request.workflowInstanceId===void 0!==(state2.workflowInstanceId===void 0))throw Error("BLOCKED: armed recovery workflow identity mismatch: request and active state disagree on workflowInstanceId presence; fail closed.");if(request.workflowInstanceId!==void 0&&state2.workflowInstanceId!==void 0&&request.workflowInstanceId!==state2.workflowInstanceId)throw Error(`BLOCKED: armed recovery workflow identity mismatch: active workflow is "${state2.workflowInstanceId}", request declared "${request.workflowInstanceId}".`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,request.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: armed recovery refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before recovering.`);if(laneSettlement.openLanes>0){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: armed recovery refused while ${laneSettlement.openLanes} PR workflow lane(s) are still in flight (lane ids: ${laneIds}). Collect their results or let them settle before recovering.`+describePrWorkflowLaneProbe(laneSettlement))}let cancelledDimensions=[],cancellations=state2.prReviewDimensionCancellations,recoveredAt=isoNow();if(state2.mode==="PR_REVIEW"&&state2.prHeadSha){let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest);for(let entry of settlement.unresolvedDimensions){if(entry.terminalState!=="NOT_LAUNCHED")continue;cancelledDimensions.push(entry.dimension)}if(cancelledDimensions.length>0){let recoveryOutcome=reducePrReviewEvent(state2,{type:"armed_recovery_requested",binding:{sessionID:state2.sessionID,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision},dimensionsToCancel:cancelledDimensions,nowIso:recoveredAt,reason:sanitizedReason});if(recoveryOutcome.status==="rejected")throw Error(`BLOCKED: armed recovery rejected (${recoveryOutcome.rejection.code}): ${recoveryOutcome.rejection.detail}`);cancellations=recoveryOutcome.state.prReviewDimensionCancellations??cancellations}}try{appendCoreEventSync(directory,{type:"pr_workflow_armed_recovery",timestamp:recoveredAt,sessionID:state2.sessionID,mode:state2.mode,prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,reason:sanitizedReason})}catch{}return await writeStateWhileLocked(directory,{...state2,updatedAt:recoveredAt,prFeedbackReadyToPublish:void 0,prFeedbackArmedRecovery:{recoveredAt,prHeadSha:state2.prHeadSha,revisionDigest:armed.revisionDigest,generation:state2.revision,reason:sanitizedReason},...cancellations?{prReviewDimensionCancellations:cancellations}:{}}),{mode:state2.mode,prHeadSha:state2.prHeadSha,openLanes:laneSettlement.openLanes,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,recoveredAt}})}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),state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)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,state2.mode),state2.prHeadSha&&state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state2.mode} workflow is bound to PR head "${state2.prHeadSha}"; received "${normalizedHead}"`);if(!state2.prHeadSha)await assertPrReviewCleanCheckout(directory,state2.mode);if(!state2.prHeadSha&&state2.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state2.prHeadSha===normalizedHead){if(state2.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state2}let nextState={...state2,prHeadSha:normalizedHead,checkoutRecovery:void 0,updatedAt:isoNow()};await _test_exports2.beforePrFeedbackTrackingPersist?.();try{return await writeStateWhileLocked(directory,nextState)}catch(error93){if(!state2.prHeadSha)try{let candidates=await resolvePrFeedbackTrackingCandidatesAsync(directory,normalizedHead);if(candidates?.local.length===1)await switchPrFeedbackTrackingCandidateAsync(directory,candidates.local[0]);else if(candidates?.remote.length===1)await switchPrFeedbackTrackingCandidateAsync(directory,candidates.remote[0]);await assertPrFeedbackTrackingCheckout(directory,normalizedHead)}catch{}throw error93}}async function rebindPrFeedbackHead(directory,sessionID,prHeadSha){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");let rebindRead=readDelegationsDetailed(directory);if(rebindRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK rebind refused while the delegation store is unreadable after ${rebindRead.attempts} attempts (${rebindRead.reason}); in-flight lanes are UNKNOWN. Restore the store before rebinding.`);let openLanes=rebindRead.records.filter((record3)=>record3.parentSessionId===state2.sessionID&&record3.mode?.startsWith("swarm-pr-")&&(record3.status==="pending"||record3.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===state2.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,state2.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state2,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state2.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{appendCoreEventSync(directory,{type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state2.sessionID,previousPrHeadSha:state2.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}catch{}return withSessionStateMutation(directory,state2.sessionID,async()=>writeStateWhileLocked(directory,nextState))}async function bindPrReviewBase(directory,sessionID,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.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(state2.prReviewBaseRef&&state2.prReviewBaseRef!==baseRef||state2.prReviewBaseSha&&state2.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state2.prReviewBaseRef??"(unbound)"}" at "${state2.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state2.prReviewBaseRef===baseRef&&state2.prReviewBaseSha===baseSha)return state2;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports2.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state2={...state2,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState2(directory,state2),state2}async function assertCurrentCheckoutHead(directory,expectedHead,mode="PR_REVIEW"){let normalizedExpected=normalizePrHeadSha(expectedHead),currentHead=(await _test_exports2.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_exports2.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_exports2.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_exports2.resolveCurrentUpstreamPushTargetAsync(directory),matchingRemoteRefs=await _test_exports2.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_exports2.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_exports2.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_exports2.afterPrFeedbackTrackingSwitch?.();let attachedHead=(await _test_exports2.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_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK requires a clean working tree after checkout attachment");let attachedUpstream=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!attachedUpstream)throw Error("BLOCKED: PR_FEEDBACK could not resolve the attached branch upstream after checkout promotion");if(!(await _test_exports2.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 state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)return null;if(toolName===DISPATCH_TOOL_NAME)return state2;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state2.mode} workflow for session "${state2.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state2}function declaredBaseDimensions(lanes){return lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])}function exactDimensionPartition(actual,expected){return actual.length===expected.length&&new Set(actual).size===expected.length&&expected.every((dimension)=>actual.includes(dimension))}function latestDelegationRecord(records){return[...records].sort((left,right)=>{let leftKey=left.completedAt??left.updatedAt??left.createdAt;return(right.completedAt??right.updatedAt??right.createdAt)-leftKey})[0]??null}function warnDelegationReadUncertainOnce(scope,uncertain){let key2=`${scope}\x00${uncertain.reason}`;if(delegationReadUncertainLogged.has(key2))return;if(delegationReadUncertainLogged.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT){let oldest=delegationReadUncertainLogged.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged.delete(oldest)}delegationReadUncertainLogged.add(key2),warn(`PR workflow gate: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); ${scope} is UNKNOWN, not absent`)}function batchLaneRecords(directory,state2,batchId,laneId){let outcome=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(outcome.status==="uncertain")return warnDelegationReadUncertainOnce("batch lane records",outcome),[];return outcome.value.filter((record3)=>record3.laneId===laneId)}function batchIsTerminal(directory,state2,batchId){let outcome=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(outcome.status==="uncertain")return warnDelegationReadUncertainOnce("batch terminality",outcome),!1;return outcome.value.length>0&&outcome.value.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record3.status)||record3.status==="consumed")}function effectivePrReviewResiliencePolicy(state2,requestedPolicy){return state2.prReviewResilience?.policy??snapshotPrReviewResiliencePolicy(requestedPolicy)}function reportCircuitAdoptionDiagnostic(diagnostic){if(diagnostic.code==="migrated_legacy_circuit"){log("PR review resilience circuit: migrated unversioned legacy circuit record to v2 CLOSED (nonblocking, evidence waterlined)",{legacyContributors:diagnostic.legacySignatureCount});return}if(malformedCircuitDiagnosticsSeen.has(diagnostic.bodyHash8))return;if(malformedCircuitDiagnosticsSeen.size>=MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT){let oldest=malformedCircuitDiagnosticsSeen.values().next().value;if(oldest!==void 0)malformedCircuitDiagnosticsSeen.delete(oldest)}malformedCircuitDiagnosticsSeen.add(diagnostic.bodyHash8),log("PR review resilience circuit: malformed circuit record dropped (fail-open)",{bodyHash8:diagnostic.bodyHash8,byteLength:diagnostic.byteLength})}function circuitOpenDurationMs(policy){return policy.circuitOpenDurationMs??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG.circuit_open_duration_ms}function laneSignalsForCircuitReview(directory,state2){let signals=[];for(let batch of state2.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state2,batch.batchId,lane.laneId));if(!latest)continue;let signal=classifyPrReviewCircuitSignal(latest);if(signal)signals.push(signal)}return signals}function probeObservationForCircuit(directory,state2,circuit){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return;let latest=latestDelegationRecord(batchLaneRecords(directory,state2,circuit.probe.batchId,circuit.probe.laneId));if(!latest)return;if(!TERMINAL_FAILED_DELEGATION_STATUSES2.has(latest.status))return;return{terminalStatus:latest.status,signal:classifyPrReviewCircuitSignal(latest),terminalAtMs:latest.terminalResult?.recordedAt??latest.completedAt??latest.updatedAt??latest.createdAt??0}}function formatPrReviewResilienceCircuitOpenMessage(circuit,nowMs3=Date.now()){if(!circuit)return"BLOCKED: PR_REVIEW resilience retry circuit is open; collect, diagnose, cancel, abort, gap reporting, and config disable remain available";if("version"in circuit){let openUntilMs=circuit.openUntil?Date.parse(circuit.openUntil):0,remainingMs=Math.max(0,openUntilMs-nowMs3),retryNote=remainingMs>0?`the recovery canary probe is admitted in about ${Math.ceil(remainingMs/1000)}s`:"the next staged dispatch is admitted as the recovery canary probe";return`BLOCKED: PR_REVIEW resilience retry circuit is ${circuit.state} after ${circuit.contributors.length} distinct terminal provider failures (${circuit.providerClass??"provider"}); ${retryNote}; collect, diagnose, cancel, abort, gap reporting, and config disable remain available`}return`BLOCKED: PR_REVIEW base dispatch circuit is open after ${circuit.count} correlated terminal failures (${circuit.signature}); collect every launched lane, then settle coverage truthfully (COMPLETE/PARTIAL/NO_COVERAGE) via complete_pr_workflow`}async function advanceResilienceCircuitWhileLocked(args2){let{directory}=args2,state2=args2.state,snapshot=args2.snapshot,nowMs3=_test_exports2.nowMs(),adoption=adoptPrReviewCircuit(snapshot.circuit,nowMs3),circuit=null;if(adoption.kind==="v2")circuit=adoption.record;else if(adoption.kind==="migrated")circuit=adoption.record,snapshot={...snapshot,circuit:adoption.record},state2=await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewResilience:snapshot}),reportCircuitAdoptionDiagnostic(adoption.diagnostic);else if(adoption.kind==="malformed"){let withoutCircuit={...snapshot};withoutCircuit.circuit=void 0,snapshot=withoutCircuit,reportCircuitAdoptionDiagnostic(adoption.diagnostic)}let advanceOutcome=reducePrReviewEvent(state2,{type:"circuit_advance_requested",nowMs:nowMs3,laneSignals:laneSignalsForCircuitReview(directory,state2),probeObservation:circuit?.state==="HALF_OPEN"?probeObservationForCircuit(directory,state2,circuit):void 0,admission:args2.admission,policy:snapshot.policy});if(advanceOutcome.status==="rejected")return{state:state2,snapshot};let nextState=advanceOutcome.state,blockedReason=advanceOutcome.effects.find((effect)=>effect.kind==="block_dispatch")?.reason;if(advanceOutcome.effects.some((effect)=>effect.kind==="persist_state"))snapshot={...snapshot,circuit:nextState.prReviewResilience?.circuit},state2=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot});else state2=nextState;if(blockedReason!==void 0)return{state:state2,snapshot,blocked:{reason:blockedReason}};let pendingProbe=nextState.prReviewResilience?.circuit;if(pendingProbe&&"version"in pendingProbe&&pendingProbe.state==="HALF_OPEN"&&pendingProbe.probe)return{state:state2,snapshot,pendingProbeCircuit:pendingProbe};return{state:state2,snapshot}}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state2,previous,policy,liveResilienceEnabled){let nextState=state2,nextPrevious=previous,snapshot=nextState.prReviewResilience;if(!snapshot){if(snapshot={policy,attempts:[]},nextPrevious.length>0)nextState=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot}),nextPrevious=nextState.prReviewBaseDispatches??[],snapshot=nextState.prReviewResilience??snapshot}if(!liveResilienceEnabled)return{state:nextState,previous:nextPrevious};let outcome=await advanceResilienceCircuitWhileLocked({directory,state:nextState,snapshot});if(outcome.blocked)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(outcome.snapshot.circuit));return{state:outcome.state,previous:outcome.state.prReviewBaseDispatches??nextPrevious}}async function probeResilienceCanaryLiveness(directory,records,timeoutMs){let session=_test_exports2.getSessionOps(),status2=session?.status;if(!session||typeof status2!=="function")return{live:!1,reason:"status probe unavailable"};let timeoutError=Error("PR workflow resilience canary probe exceeded its deadline"),response;try{response=await withTimeout((async()=>status2.call(session,{query:{directory}}))(),timeoutMs,timeoutError)}catch(error93){return{live:!1,reason:error93===timeoutError?"status probe timed out":"status probe failed"}}if(response?.error)return{live:!1,reason:"status probe errored"};if(!response?.data)return{live:!1,reason:"status probe returned no data"};for(let record3 of records){let type=response.data[record3.subagentSessionId]?.type;if(type==="busy"||type==="retry")return{live:!0}}return{live:!1,reason:"status probe did not report busy/retry"}}async function evaluatePrReviewResilienceAttempt(directory,state2,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest),remaining=attempt.targetDimensions.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension)),inFlight=attempt.targetDimensions.filter((dimension)=>attempts.inFlight.has(dimension));if(remaining.length===0&&inFlight.length===0)return{remaining:[],inFlight:[],canaryState:"success",fanoutSettled:Boolean(attempt.fanoutBatchId)};if(attempts.successful.has(attempt.canaryWorkflowLane))return{remaining,inFlight,canaryState:"success",fanoutSettled:attempt.fanoutBatchId?batchIsTerminal(directory,state2,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state2,attempt.canaryBatchId,attempt.canaryLaneId);if(canaryRecords.length>0&&canaryRecords.every((record3)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record3.status)))return{remaining,inFlight,canaryState:"failed",fanoutSettled:!1};let admittedAtMs=Date.parse(attempt.admittedAt);if(Number.isFinite(admittedAtMs)&&_test_exports2.nowMs()-admittedAtMs<policy.canaryProbeMs)return{remaining,inFlight,canaryState:"waiting",reason:"canary probe horizon has not elapsed yet",fanoutSettled:!1};let probe2=await probeResilienceCanaryLiveness(directory,canaryRecords,policy.statusProbeTimeoutMs);if(probe2.live)return{remaining,inFlight,canaryState:"live",fanoutSettled:!1};return{remaining,inFlight,canaryState:"waiting",reason:probe2.reason,fanoutSettled:!1}}function unresolvedPrReviewBaseDimensions(attempts){return PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>!attempts.successful.has(dimension)&&!attempts.inFlight.has(dimension))}async function enforcePrReviewBaseDimensions(directory,sessionID,lanes,options){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options)))}async function enforcePrReviewBaseDimensionsWhileLocked(directory,normalizedSessionID,lanes,options){let state2=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state2.mode!=="PR_REVIEW")throw wrongModeError(state2,"PR_REVIEW");let normalizedLanes=normalizeWorkflowLanes(lanes),claimedDimensionIds=declaredBaseDimensions(normalizedLanes);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((state2.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state2,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=state2.prReviewBaseDispatches??[];if(previous.some((record4)=>record4.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);let depthTier=state2.prReviewDepthTier??"L",requestedContractRetry=options.prReviewContractRetry===!0,requestedWaveStage=options.prReviewWaveStage,requestedWaveAttempt=options.prReviewWaveAttempt;if(requestedContractRetry&&(requestedWaveStage!==void 0||requestedWaveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");if(requestedWaveStage===void 0!==(requestedWaveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");let resiliencePolicy=effectivePrReviewResiliencePolicy(state2,options.prReviewResiliencePolicy),liveResilienceEnabled=options.prReviewResiliencePolicy?.enabled??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG.enabled;if(previous.length>=MAX_WORKFLOW_BATCHES&&requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0&&depthTier!=="S"&&liveResilienceEnabled)({state:state2,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state2,previous,resiliencePolicy,liveResilienceEnabled));if(previous.length>=MAX_WORKFLOW_BATCHES){if(state2=await prunePrWorkflowBatchesForCapacity(directory,state2,options.revisionDigest),previous=state2.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let nextResilience=state2.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state2=await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state2.prReviewBaseDispatches??[]}if(nextResilience&&(!liveResilienceEnabled||nextResilience.policy.enabled===!1)){let configEvent={type:"resilience_config_changed",enabled:liveResilienceEnabled,policy:liveResilienceEnabled?options.prReviewResiliencePolicy:void 0,nowMs:_test_exports2.nowMs()},outcome=reducePrReviewEvent(state2,configEvent);if(outcome.status==="applied"&&outcome.effects.some((effect)=>effect.kind==="persist_state"))state2=await writeStateWhileLocked(directory,{...outcome.state,updatedAt:isoNow()}),previous=state2.prReviewBaseDispatches??[],nextResilience=state2.prReviewResilience??nextResilience}if(liveResilienceEnabled&&depthTier!=="S"&&requestedWaveStage===void 0&&!requestedContractRetry)throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first staged admission while pr_review_resilience is enabled");if(requestedWaveStage!==void 0&&requestedWaveAttempt!==void 0){if(depthTier==="S"||!liveResilienceEnabled)throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");let revisionDigest=options.revisionDigest;if(!revisionDigest)revisionDigest=(await createPrReviewGateContext2(directory,state2)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]},pendingProbeCircuit;if(liveResilienceEnabled){let outcome=await advanceResilienceCircuitWhileLocked({directory,state:state2,snapshot,admission:{batchId,laneId:normalizedLanes[0]?.laneId??""}});if(state2=outcome.state,snapshot=outcome.snapshot,nextResilience=outcome.snapshot,pendingProbeCircuit=outcome.pendingProbeCircuit,outcome.blocked)throw new PrReviewResilienceCircuitOpenError(formatPrReviewResilienceCircuitOpenMessage(outcome.snapshot.circuit))}let lastAttempt=snapshot.attempts.at(-1);if(requestedWaveStage==="canary"){let target=[...PR_REVIEW_BASE_DIMENSION_IDS],expectedAttempt=0,globalInFlight=[];if(lastAttempt){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state2,lastAttempt,revisionDigest,snapshot.policy);if(!lastAttempt.fanoutBatchId)if(evaluated.canaryState==="success"){if(evaluated.remaining.length>0)throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} requires its fanout batch before a later retry attempt`);if(globalTarget.length===0)throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining");target=[...globalTarget]}else{if(evaluated.canaryState==="live")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is still live; fanout is the next admissible stage`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);target=[...globalTarget]}else{if(!batchIsTerminal(directory,state2,lastAttempt.fanoutBatchId))throw Error(`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} fanout is still in flight`);target=[...globalTarget]}expectedAttempt=lastAttempt.attempt+1}else if(previous.length>0){let globalAttempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension)),target=unresolvedPrReviewBaseDimensions(globalAttempts)}if(target.length===0){if(globalInFlight.length>0)throw Error(lastAttempt?`BLOCKED: PR_REVIEW base attempt ${lastAttempt.attempt} still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`:`BLOCKED: PR_REVIEW base still has in-flight obligations that cannot be retried yet: ${globalInFlight.join(", ")}`);throw new PrReviewResilienceRetryExhaustedError("BLOCKED: PR_REVIEW base dispatch has no unresolved obligations remaining")}if(requestedWaveAttempt!==expectedAttempt||requestedWaveAttempt>snapshot.policy.maxRetryAttemptsAfterInitial)throw new PrReviewResilienceRetryExhaustedError(`BLOCKED: PR_REVIEW base allows attempt 0 plus at most ${snapshot.policy.maxRetryAttemptsAfterInitial} retry attempts`);if(normalizedLanes.length!==1||(normalizedLanes[0]?.ownedWorkflowLanes?.length??1)!==1)throw Error("BLOCKED: PR_REVIEW staged canary dispatch requires exactly one singleton base lane");let canaryDimension=normalizedLanes[0].workflowLane;if(!target.includes(canaryDimension))throw Error(`BLOCKED: PR_REVIEW canary lane must target one unresolved base obligation from: ${target.join(", ")}`);nextResilience={policy:snapshot.policy,attempts:[...snapshot.attempts,{attempt:requestedWaveAttempt,targetDimensions:target,canaryBatchId:batchId,canaryLaneId:normalizedLanes[0].laneId,canaryWorkflowLane:canaryDimension,admittedAt:isoNow()}],...pendingProbeCircuit??snapshot.circuit?{circuit:pendingProbeCircuit??snapshot.circuit}:{}}}else{if(!lastAttempt||lastAttempt.attempt!==requestedWaveAttempt||lastAttempt.fanoutBatchId)throw Error(`BLOCKED: PR_REVIEW base fanout must follow the recorded canary for attempt ${requestedWaveAttempt}`);let evaluated=await evaluatePrReviewResilienceAttempt(directory,state2,lastAttempt,revisionDigest,snapshot.policy);if(evaluated.canaryState==="failed")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary failed; close the attempt and carry the unresolved target into the next retry`);if(evaluated.canaryState==="waiting")throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} canary is not yet proven successful or live: ${evaluated.reason??"probe failed closed"}`);let remainingTarget=lastAttempt.targetDimensions.filter((dimension)=>dimension!==lastAttempt.canaryWorkflowLane&&evaluated.remaining.includes(dimension));if(remainingTarget.length===0)throw Error(`BLOCKED: PR_REVIEW base attempt ${requestedWaveAttempt} has no remaining unresolved obligations for fanout`);if(!exactDimensionPartition(declaredBaseDimensions(normalizedLanes),remainingTarget))throw Error(`BLOCKED: PR_REVIEW base fanout must partition the remaining unresolved obligations exactly once: ${remainingTarget.join(", ")}`);if(requestedWaveAttempt===0){let combinedDimensions=[lastAttempt.canaryWorkflowLane,...declaredBaseDimensions(normalizedLanes)];if(!exactDimensionPartition(combinedDimensions,lastAttempt.targetDimensions))throw Error("BLOCKED: PR_REVIEW base attempt 0 canary plus fanout must partition all six base dimensions exactly once");if(depthTier==="M"&&normalizedLanes.length+1<PR_REVIEW_BASE_LANE_FLOORS.M)throw Error(`BLOCKED: PR_REVIEW base attempt 0 at depth tier M requires at least ${PR_REVIEW_BASE_LANE_FLOORS.M} combined canary+fanout lanes`);if(depthTier==="L"&&(normalizedLanes.length+1!==PR_REVIEW_BASE_DIMENSION_IDS.length||normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)))throw Error("BLOCKED: PR_REVIEW base attempt 0 at depth tier L requires six singleton combined canary+fanout lanes")}nextResilience={...snapshot,attempts:[...snapshot.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:batchId}]}}}if(requestedContractRetry){let revisionDigest=options.revisionDigest??(await createPrReviewGateContext2(directory,state2)).revisionDigest,attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,revisionDigest);if(normalizedLanes.length!==1||(normalizedLanes[0]?.ownedWorkflowLanes?.length??1)!==1)throw Error("BLOCKED: PR_REVIEW contract retry requires exactly one singleton lane");let contractedDimension=declaredBaseDimensions(normalizedLanes)[0]??normalizedLanes[0].workflowLane;if(attempts.successful.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry cannot target already-successful dimension "${contractedDimension}"`);if(attempts.inFlight.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry cannot target in-flight dimension "${contractedDimension}"`);if(!attempts.contractFailed.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry requires a recorded terminal contract failure for dimension "${contractedDimension}"`);if(attempts.contractRetried.has(contractedDimension))throw Error(`BLOCKED: PR_REVIEW contract retry for dimension "${contractedDimension}" was already admitted`)}let record3={batchId,lanes:normalizedLanes.map((lane)=>({laneId:lane.laneId,workflowLane:lane.workflowLane,...lane.ownedWorkflowLanes?{ownedWorkflowLanes:lane.ownedWorkflowLanes}:{}})),validatedAt:isoNow()},admissionOutcome=reducePrReviewEvent(state2,{type:"base_admission_requested",batchId,lanes:record3.lanes,maxBatches:MAX_WORKFLOW_BATCHES,validatedAt:record3.validatedAt});if(admissionOutcome.status==="rejected")throw Error("BLOCKED: PR_REVIEW base batch limit reached");let nextState={...admissionOutcome.state,updatedAt:isoNow(),...requestedContractRetry?{prReviewContractRetryDimensions:[...state2.prReviewContractRetryDimensions??[],declaredBaseDimensions(normalizedLanes)[0]]}:{},...nextResilience?{prReviewResilience:nextResilience}:{}};return writeStateWhileLocked(directory,nextState)}async function rollbackPrReviewBaseAdmissionIfUnlaunched(directory,sessionID,batchId,contractRetry=!1){let normalizedSessionID=normalizeSessionID(sessionID),normalizedBatchId=normalizeBatchId(batchId);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_REVIEW")return!1;let batchRead=findByBatchIdDetailed(directory,normalizedBatchId,{parentSessionId:normalizedSessionID});if(batchRead.status==="uncertain")return warnDelegationReadUncertainOnce("base admission rollback existence guard",batchRead),!1;let batchRecords=batchRead.value,rollbackOutcome=reducePrReviewEvent(state2,{type:"base_admission_rolled_back",batchId:normalizedBatchId,batchDelegationRecordsExist:batchRecords.length>0});if(rollbackOutcome.status==="rejected")return!1;let rollbackState=rollbackOutcome.state,currentBaseDispatches=state2.prReviewBaseDispatches??[],nextBaseDispatches=rollbackState.prReviewBaseDispatches??[],rolledBackDimensions=new Set(currentBaseDispatches.at(-1)?.lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])??[]),nextContractRetryDimensions=contractRetry?(state2.prReviewContractRetryDimensions??[]).filter((dimension)=>!rolledBackDimensions.has(dimension)):state2.prReviewContractRetryDimensions,lastAttempt=state2.prReviewResilience?.attempts.at(-1),nextResilience=rollbackState.prReviewResilience;if(lastAttempt?.canaryBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:nextResilience.attempts.slice(0,-1)}:nextResilience;else if(lastAttempt?.fanoutBatchId===normalizedBatchId)nextResilience=nextResilience?{...nextResilience,attempts:[...nextResilience.attempts.slice(0,-1),{...lastAttempt,fanoutBatchId:void 0}]}:nextResilience;let rolledBackCircuit=nextResilience?.circuit;if(rolledBackCircuit&&"version"in rolledBackCircuit&&rolledBackCircuit.state==="HALF_OPEN"&&rolledBackCircuit.probe?.batchId===normalizedBatchId){let probeOutcome=reducePrReviewEvent({...rollbackState,prReviewResilience:nextResilience},{type:"circuit_probe_settled",outcome:{result:"rolled_back_admission"},nowMs:_test_exports2.nowMs(),policy:{...nextResilience?.policy??snapshotPrReviewResiliencePolicy(),circuitOpenDurationMs:circuitOpenDurationMs(nextResilience?.policy??snapshotPrReviewResiliencePolicy())}});if(probeOutcome.status==="applied")nextResilience=probeOutcome.state.prReviewResilience??nextResilience}let shouldKeepResilience=nextBaseDispatches.length>0&&Boolean(nextResilience?.policy)||Boolean(nextResilience?.circuit)||(nextResilience?.attempts.length??0)>0;return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewBaseDispatches:nextBaseDispatches,...nextBaseDispatches.length>0?{prReviewBaseDispatch:nextBaseDispatches.at(-1)}:{prReviewBaseDispatch:void 0},...shouldKeepResilience?{prReviewResilience:nextResilience}:{prReviewResilience:void 0},...nextContractRetryDimensions?.length?{prReviewContractRetryDimensions:nextContractRetryDimensions}:{prReviewContractRetryDimensions:void 0}}),!0}))}function encodeConsolidatedLaneKey(owned){return[...new Set(owned)].sort().join("|")}function decodeConsolidatedLaneKey(key2){return key2.split("|").filter((dimension)=>dimension.length>0)}function minimumConsolidatedLaneCover(sets){let bitOf=new Map;for(let set3 of sets)for(let dimension of set3)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 set3 of sets){let mask=0,size=0;for(let dimension of set3){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(state2,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 state2.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key2 of state2.prReviewRetiredConsolidatedLanes??[])consider(decodeConsolidatedLaneKey(key2),!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,state2,normalizedLanes,revisionDigest){if((state2.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 digest3=revisionDigest;if(!digest3)digest3=(await createPrReviewGateContext2(directory,state2)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state2,digest3),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(state2,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,state2,revisionDigest){try{let digest3=revisionDigest??(await createPrReviewGateContext2(directory,state2)).revisionDigest,before={candidate:derivePrReviewCandidateInventory2(directory,state2,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,state2,{revisionDigest:digest3})},pruned=pruneWorkflowBatches(directory,state2,digest3);if(!pruned)return state2;let after={candidate:derivePrReviewCandidateInventory2(directory,pruned,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,pruned,{revisionDigest:digest3})};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"),state2;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state2.prReviewBaseDispatch&&!survivingBaseIds.has(state2.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state2;return pruned}catch(error93){return warn(`PR_REVIEW batch GC aborted: ${error93 instanceof Error?error93.message:String(error93)}`),state2}}function pruneWorkflowBatches(directory,state2,revisionDigest){let baseBatches=state2.prReviewBaseDispatches??[],validationBatches=state2.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful2=successfulObligationsFromExactBatch2(directory,state2,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)=>successful2.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,state2,"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(state2.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")return warnDelegationReadUncertainOnce("retired-reviewer session collection",batchRead),null;for(let record3 of batchRead.value){let subagentSessionId=record3.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(state2.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(state2.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state2,...state2.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state2.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 admitPrReviewPartialBaseCoverage2(directory,sessionID,runId,unresolvedDimensions){return await admitPrReviewPartialBaseCoverage(directory,sessionID,runId,unresolvedDimensions)}async function assertPrReviewBaseCoverageSettled2(directory,sessionID,gateContext){let settled=await assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext);return{state:settled.state,settlement:settled.settlement}}async function recordPrReviewValidationBatch(directory,sessionID,phase,lanes,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_REVIEW")throw wrongModeError(state2,"PR_REVIEW");if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext2(directory,state2);if(phase==="reviewer"&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state2=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state2=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"?derivePrReviewCandidateInventory2(directory,state2,ctx):derivePrReviewCriticInventory2(directory,state2,ctx),assertStringSetSubset(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state2.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(state2=await prunePrWorkflowBatchesForCapacity(directory,state2,ctx.revisionDigest),previous=state2.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record3={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state2,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state2.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state2.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};let nextState={...state2,updatedAt:isoNow(),prReviewValidationBatches:[...retained,record3],prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0};return await persistState2(directory,nextState),nextState}async function assertPrReviewValidationSettled(directory,sessionID,phase,gateContext){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext2(directory,state2),declaredPhases=new Set((state2.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state2.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow2(state2,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 successfulObligationsFromExactBatch2(directory,state2,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,state2,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,state2,ctx):deriveLatestPrReviewCriticVerdicts(directory,state2,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 state2}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state2.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId2)=>!inventorySet.has(findingId2));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state2.prFeedbackInventory){let existing=state2.prFeedbackInventory;if(sameStringArray(existing,normalizedInventory))return state2;let nextIds=new Set(normalizedInventory),droppedIds=existing.filter((itemId)=>!nextIds.has(itemId));if(droppedIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory is append-only after declaration; declared item(s) may not be removed or renamed: ${droppedIds.join(", ")}`);let existingIds=new Set(existing),appendedIds=normalizedInventory.filter((itemId)=>!existingIds.has(itemId));if(appendedIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory amendment declared no new items");let previousAmendments=state2.prFeedbackInventoryAmendments??[];if(previousAmendments.length+appendedIds.length>MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS)throw Error(`BLOCKED: PR_FEEDBACK inventory amendment limit reached (${MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS}); the amendment ledger is an audit trail and is never pruned`);let amendedAt=isoNow(),batch=previousAmendments.reduce((highest,amendment)=>Math.max(highest,amendment.batch),0)+1,amendedState={...state2,updatedAt:amendedAt,prFeedbackInventory:normalizedInventory,prFeedbackInventoryAmendments:[...previousAmendments,...appendedIds.map((entry)=>({entry,amendedAt,batch}))],prFeedbackReadyToPublish:void 0},superseded=supersedeLivePublicationInPendingState(amendedState,"inventory-amended");if(await persistState2(directory,superseded.state),superseded.invalidationEvent)appendPublicationEvent(directory,superseded.invalidationEvent);return superseded.state}let nextState={...state2,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState2(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state2){try{let digest3=await currentPrFeedbackRevisionDigest(directory,state2),batches=state2.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state2,digest3),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state2,batch,digest3).size>0);if(surviving.length===batches.length)return state2;let retiredItemOwnership={...state2.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"),state2;let pruned={...state2,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest3);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state2;if(state2.prFeedbackVerification&&!survivingIds.has(state2.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state2;return pruned}catch(error93){return warn(`PR_FEEDBACK verification GC aborted: ${error93 instanceof Error?error93.message:String(error93)}`),state2}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let inventory=state2.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state2.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state2.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record4)=>record4.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state2=await prunePrFeedbackVerificationsForCapacity(directory,state2),previous=state2.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state2.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record4 of previous)for(let lane of record4.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 record3={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record3],prFeedbackVerification:record3};return await persistState2(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state2,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch2(directory,state2,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(!legacyFeedbackArtifactCoversItems(directory,state2,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state2,currentDigest){let covered=new Set;for(let batch of state2.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state2,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettledState(directory,state2){if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state2),inventory=state2.prFeedbackInventory,batches=state2.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state2,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 currentDigest}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK");return await assertPrFeedbackVerificationSettledState(directory,state2),state2}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks5,options={}){let state2=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks5.length<2||checks5.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)=>checks5.some((check3)=>check3.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 required3=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 check3 of checks5){if(["diff-check","reproduction"].includes(check3.category)&&singletonSeen.has(check3.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check3.category}"`);if(singletonSeen.add(check3.category),required3.delete(check3.category),check3.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check3.obligationId);if(!obligation||obligation.category!==check3.category||obligation.workingDirectory!==(check3.workingDirectory??".")||!requiredObligationIds.delete(check3.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check3.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&&(check3.validatorContract?.path!==requiredContract.path||check3.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash53("sha256").update(`${check3.obligationId??check3.category}\x00${check3.workingDirectory??"."}\x00${check3.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),check3.category==="diff-check"&&!sameStringArray(check3.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check3.category==="reproduction"&&(!check3.targets?.length||!check3.feedbackTargets?.length||check3.targets.some((target)=>!check3.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check3.category==="reproduction"){if(reproductionFeedbackItemIds=check3.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check3.feedbackTargets.some((mapping)=>!check3.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required3.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required3].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state2.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(state2.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state2,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks5],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state2.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0},superseded=supersedeLivePublicationInPendingState(nextState,"stage-a-rerun");if(await persistState2(directory,superseded.state),superseded.invalidationEvent)appendPublicationEvent(directory,superseded.invalidationEvent);return superseded.state}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 state2=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state2.mode!=="PR_FEEDBACK")throw wrongModeError(state2,"PR_FEEDBACK");let inventory=state2.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)state2=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state2,currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);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=state2.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),record3={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record3]};return await persistState2(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state2=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state2);if(state2.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state2.prFeedbackStageA?.feedbackItemIds??[],state2.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state2.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(!sameStringArray(batch.itemIds,state2.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} evidence covers a stale inventory; the feedback inventory was amended after this batch was recorded. Re-run ${phase} against every current inventory item.`);if(!successfulObligationsFromExactBatch2(directory,state2,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`);let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK ${phase} gate cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's durable child record is UNKNOWN, not absent. Restore the store and re-validate.`);if(batchRead.value.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,state2,phase),state2}function assertIndependentFeedbackGateSessions(directory,state2,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state2.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let batchRead=findByBatchIdDetailed(directory,batch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's durable child session is UNKNOWN, not absent. Restore the store and re-validate.`);let matching=batchRead.value.filter((record4)=>record4.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record3=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record3.normalizedAgent===expectedRole||expectedRole==="critic"&&record3.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record3.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record3.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record3.subagentSessionId}"`);seenSessions.add(record3.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state2=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state2=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state2}function deriveReadyToPublishMirror(active){if(!active||active.state!=="armed"&&active.state!=="push_in_flight")return;return{revisionDigest:active.revisionDigest,localHead:active.localHead,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,remoteRef:active.remoteRef,validatedAt:active.armedAt??active.createdAt}}async function verifyPublicationIdentityComponent(directory,state2,active,component){switch(component){case"digest":try{let digest3=await currentPrFeedbackRevisionDigest(directory,state2);return digest3===active.revisionDigest?{kind:"intact"}:{kind:"drift",component,detail:`approved revision digest ${active.revisionDigest} vs current ${digest3}`}}catch(error93){return{kind:"unresolvable",component,detail:String(error93?.message??error93)}}case"head":{let head=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!head)return{kind:"unresolvable",component,detail:"HEAD resolution returned empty"};return head===active.localHead?{kind:"intact"}:{kind:"drift",component,detail:`approved head ${active.localHead} vs current ${head}`}}case"worktree":{let clean=await _test_exports2.resolveIsWorkingTreeCleanAsync(directory);if(clean!==!0&&clean!==!1)return{kind:"unresolvable",component,detail:"clean-status resolution failed"};return clean===!0?{kind:"intact"}:{kind:"drift",component,detail:"working tree or index is dirty"}}case"upstream":{let target=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!target)return{kind:"unresolvable",component,detail:"upstream target resolution returned empty"};return target.remoteName===active.remoteName&&target.remoteBranchRef===active.remoteBranchRef&&target.remoteTrackingRef===active.remoteRef?{kind:"intact"}:{kind:"drift",component,detail:`approved target ${active.remoteName}/${active.remoteBranchRef}/${active.remoteRef} vs current ${target.remoteName}/${target.remoteBranchRef}/${target.remoteTrackingRef}`}}case"remote-url":{if(!active.remoteUrlIdentity)return{kind:"unresolvable",component,detail:"armed generation carries no remote URL identity"};let url3=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,active.remoteName);if(!url3)return{kind:"unresolvable",component,detail:`remote "${active.remoteName}" URL could not be resolved`};return url3===active.remoteUrlIdentity?{kind:"intact"}:{kind:"drift",component,detail:`approved remote URL identity ${active.remoteUrlIdentity} vs current ${url3}`}}case"workspace-identity":{let identity=canonicalWorkspaceIdentity(directory);if(!identity)return{kind:"unresolvable",component,detail:"canonical workspace identity could not be resolved"};return identity===active.workspaceIdentity?{kind:"intact"}:{kind:"drift",component,detail:"generation is bound to a different workspace"}}case"evidence-join":return publicationEvidenceJoinIntact(state2,active)?{kind:"intact"}:{kind:"drift",component,detail:"the receipt set recorded at arming is no longer the active one"};default:return{kind:"unresolvable",component,detail:"unknown component"}}}async function checkPublicationIdentity(directory,state2,active){for(let component of PUBLICATION_IDENTITY_COMPONENTS){let check3=await verifyPublicationIdentityComponent(directory,state2,active,component);if(check3.kind!=="intact")return check3}if(!publicationEvidenceJoinIntact(state2,active))return{kind:"drift",component:"evidence-join",detail:"the receipt set recorded at arming is no longer the active one"};return{kind:"intact"}}function publicationEvidenceJoinIntact(state2,active){if(state2.prFeedbackStageA?.validatedAt!==active.evidence.stageAValidatedAt)return!1;for(let join84 of active.evidence.batches){let batch=[...state2.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===join84.phase);if(!batch||batch.batchId!==join84.batchId||batch.laneId!==join84.laneId)return!1}return!0}function buildPublicationEvidenceJoin(state2,currentDigest){let stageA=state2.prFeedbackStageA;if(!stageA||stageA.revisionDigest!==currentDigest||!stageA.validatedAt)return null;let batches=[];for(let phase of PR_FEEDBACK_PHASE_ORDER){let batch=[...state2.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase&&candidate.revisionDigest===currentDigest);if(!batch)return null;batches.push({phase,batchId:batch.batchId,laneId:batch.laneId})}return{stageAValidatedAt:stageA.validatedAt,batches}}function appendPublicationEvent(directory,event){try{appendCoreEventSync(directory,{...event,timestamp:isoNow()})}catch{}}function boundPublicationDiagnostic(text){let redacted=redactSecrets(text).replace(PUBLICATION_URL_CREDENTIALS_PATTERN,"$1[REDACTED:url_credentials]@");return redacted.length>MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS?`${redacted.slice(0,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS-3)}...`:redacted}function nextPublicationContainer(previous,active,historyAppends=[],attempts=[]){let history=[...previous?.history??[],...historyAppends].slice(-MAX_PUBLICATION_HISTORY_GENERATIONS);return{schemaVersion:PUBLICATION_SCHEMA_VERSION,active,history,attempts:attempts.slice(-MAX_PUBLICATION_ATTEMPTS)}}async function invalidatePublicationGeneration(directory,sessionID,reason,options={}){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")throw Error("BLOCKED: PR_FEEDBACK publication invalidation requires an active PR_FEEDBACK gate");return applyPublicationInvalidationWhileLocked(directory,state2,reason,options)})}async function applyPublicationInvalidationWhileLocked(directory,state2,reason,options={}){{let active=state2.prFeedbackPublication?.active,legacyRecord=active?void 0:state2.prFeedbackReadyToPublish;if(!active&&!legacyRecord)throw Error("BLOCKED: no armed publication generation to invalidate");if(active&&active.state!=="armed"&&active.state!=="push_in_flight")throw Error(`BLOCKED: publication generation ${active.generation} is already ${active.state}`);if(options.driftReverification&&options.drift&&active){let recheck=await verifyPublicationIdentityComponent(directory,state2,active,options.drift.component);if(recheck.kind!=="drift")throw Error(`BLOCKED: PR_FEEDBACK publication drift on ${options.drift.component} did not re-confirm under the state lock (${recheck.kind}); no invalidation was recorded — retry from current state`);options.drift={component:recheck.component,detail:recheck.detail}}let now=isoNow(),attempts=(state2.prFeedbackPublication?.attempts??[]).map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:options.finalizeInFlightAs??"uncertain",exitStatus:"not-observed",diagnostic:`finalized by publication invalidation (${reason})`,postPush:{localHead:null,observedRemoteHead:null},completedAt:now}}),invalidated;if(active)invalidated={...active,state:"invalidated",invalidatedAt:now,invalidationReason:reason};else if(legacyRecord)invalidated={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:1,state:"invalidated",workspaceIdentity:canonicalWorkspaceIdentity(directory)??"unresolvable",sessionID:state2.sessionID,intakeHeadSha:state2.prHeadSha??"unknown",localHeadRef:"unknown",localHead:legacyRecord.localHead,remoteName:legacyRecord.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacyRecord.remoteBranchRef,remoteRef:legacyRecord.remoteRef,revisionDigest:legacyRecord.revisionDigest,evidence:{stageAValidatedAt:state2.prFeedbackStageA?.validatedAt??"unknown",batches:(state2.prFeedbackGateBatches??[]).map((batch)=>({phase:batch.phase,batchId:batch.batchId,laneId:batch.laneId}))},invalidationReason:reason,createdAt:legacyRecord.validatedAt,armedAt:legacyRecord.validatedAt,invalidatedAt:now};else throw Error("BLOCKED: no armed publication generation to invalidate");if(!active)attempts=[];let nextState={...state2,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,invalidated,[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_invalidated",sessionID:state2.sessionID,generation:invalidated.generation,reason,previousState:active?.state??"armed",drift:options.drift??null,revisionDigest:invalidated.revisionDigest,localHead:invalidated.localHead,remoteName:invalidated.remoteName,remoteBranchRef:invalidated.remoteBranchRef,supersededBatchIds:invalidated.evidence.batches.map((b)=>b.batchId)}),{generation:invalidated,state:nextState}}}async function ensurePublicationGenerationCurrent(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),state2=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return state2;if(state2.prFeedbackPublication||!state2.prFeedbackReadyToPublish)return state2;let legacy=state2.prFeedbackReadyToPublish;return withSessionStateMutation(directory,normalizedSessionID,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!locked||locked.mode!=="PR_FEEDBACK")return locked??state2;if(locked.prFeedbackPublication||!locked.prFeedbackReadyToPublish)return locked;let now=isoNow(),base={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:1,sessionID:locked.sessionID,prTargetUrl:locked.prFeedbackTargetUrl,intakeHeadSha:locked.prHeadSha??"unknown",revisionDigest:legacy.revisionDigest,evidence:buildPublicationEvidenceJoin(locked,legacy.revisionDigest)??{stageAValidatedAt:"unknown",batches:[]},createdAt:legacy.validatedAt,armedAt:legacy.validatedAt},mismatch=async(reason)=>{let invalidated={...base,evidence:base.evidence.batches.length>0?base.evidence:{stageAValidatedAt:locked.prFeedbackStageA?.validatedAt??"unknown",batches:(locked.prFeedbackGateBatches??[]).map((batch)=>({phase:batch.phase,batchId:batch.batchId,laneId:batch.laneId}))},state:"invalidated",workspaceIdentity:canonicalWorkspaceIdentity(directory)??"unresolvable",localHeadRef:"unknown",localHead:legacy.localHead,remoteName:legacy.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacy.remoteBranchRef,remoteRef:legacy.remoteRef,invalidationReason:reason,invalidatedAt:now},nextState2={...locked,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(locked.prFeedbackPublication,invalidated)};return await writeStateWhileLocked(directory,nextState2),appendPublicationEvent(directory,{type:"pr_feedback_publication_migrated",sessionID:locked.sessionID,generation:1,outcome:"invalidated",reason}),nextState2};if(locked.prFeedbackStageA?.revisionDigest!==legacy.revisionDigest||!(locked.prFeedbackGateBatches??[]).some((batch)=>batch.revisionDigest===legacy.revisionDigest))return mismatch("legacy-migration-receipt-mismatch");let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)return mismatch("legacy-migration-unresolvable");let digest3;try{digest3=await currentPrFeedbackRevisionDigest(directory,locked)}catch{return mismatch("legacy-migration-unresolvable")}let head=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),target=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory),localHeadRef=await resolveCurrentLocalHeadRefAsync(directory),remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,legacy.remoteName);if(digest3!==legacy.revisionDigest||head!==legacy.localHead||!target||target.remoteName!==legacy.remoteName||target.remoteBranchRef!==legacy.remoteBranchRef||target.remoteTrackingRef!==legacy.remoteRef||!localHeadRef||!remoteUrlIdentity)return mismatch("legacy-migration-identity-mismatch");let evidenceJoin=buildPublicationEvidenceJoin(locked,legacy.revisionDigest);if(!evidenceJoin)return mismatch("legacy-migration-receipt-mismatch");let upgraded={...base,evidence:evidenceJoin,state:"armed",workspaceIdentity,localHeadRef,localHead:legacy.localHead,remoteName:legacy.remoteName,remoteUrlIdentity,remoteBranchRef:legacy.remoteBranchRef,remoteRef:legacy.remoteRef},nextState={...locked,updatedAt:now,prFeedbackPublication:nextPublicationContainer(locked.prFeedbackPublication,upgraded)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_migrated",sessionID:locked.sessionID,generation:1,outcome:"armed",reason:"legacy-record-proven-equivalent"}),nextState})}async function reconcileForeignInFlightAttempt(directory,sessionID,currentCallId){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active||active.state!=="push_in_flight"||!publication.attempts.some((attempt)=>!attempt.result))return state2;let now=isoNow(),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),attempts=publication.attempts.map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"uncertain",exitStatus:"not-observed",diagnostic:boundPublicationDiagnostic(`recovered without an observed result${currentCallId&&attempt.callID===currentCallId?" (same call)":""}`),postPush:{localHead:localHead??null,observedRemoteHead},completedAt:now}}),nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome:"uncertain",by:"reaper",observedRemoteHead}),nextState})}async function invalidatePrFeedbackPublication(directory,sessionID,reason){let trimmed=reason.trim();if(!trimmed)throw Error("BLOCKED: invalidate_pr_feedback_publication requires a non-empty reason; the reason is part of the durable audit trail");return await ensurePublicationGenerationCurrent(directory,sessionID),await reconcileForeignInFlightAttempt(directory,sessionID),(await invalidatePublicationGeneration(directory,sessionID,`controller-rework:${trimmed}`)).generation}function describePrWorkflowPublicationSection(state2){let active=state2.prFeedbackPublication?.active,history=state2.prFeedbackPublication?.history??[],attempts=state2.prFeedbackPublication?.attempts??[];if(!active&&!state2.prFeedbackReadyToPublish&&history.length===0)return null;let lines=[];if(state2.prFeedbackReadyToPublish&&!active)lines.push("publication: legacy armed record awaiting generation migration (fail-closed until the next gated interaction migrates it)");if(active){if(lines.push(`publication: generation ${active.generation} state=${active.state}`),lines.push(` approved: ${active.localHead} -> ${active.remoteName} ${active.remoteBranchRef} (digest ${active.revisionDigest.slice(0,12)}…)`),active.remoteUrlIdentity)lines.push(` remote url identity: ${active.remoteUrlIdentity}`);if(active.state==="invalidated"&&active.invalidationReason)lines.push(` invalidated because: ${active.invalidationReason}`);if(active.supersededByGeneration)lines.push(` superseded by generation ${active.supersededByGeneration}`);let generationAttempts=attempts.filter((attempt)=>attempt.generation===active.generation);if(generationAttempts.length>0){let outcomes=generationAttempts.map((attempt)=>attempt.result?.outcome??"in-flight");lines.push(` push attempts: ${generationAttempts.length} (${outcomes.join(", ")})`)}switch(active.state){case"armed":lines.push(" next: run the exact approved push, then complete_pr_workflow");break;case"push_in_flight":lines.push(" next: a push attempt is in flight; the next gated interaction reconciles it (uncertain) and re-verifies the remote before any retry");break;case"invalidated":lines.push(" next: rerun Stage A and every independent gate on the corrected content, then arm a fresh generation with complete_pr_workflow; the exact scoped rework path reopens via prepare_pr_feedback_scope");break;case"published":lines.push(" terminal: published (verified remote head)");break;case"cancelled_without_publication":lines.push(" terminal: cancelled without publication");break;default:lines.push(" next: continue the ordered gates")}}if(history.length>0){let summary=history.map((generation)=>`gen ${generation.generation}: ${generation.state}${generation.supersededByGeneration?` -> ${generation.supersededByGeneration}`:""}`).join("; ");lines.push(` superseded generations: ${summary}`)}return lines.push(" audit: full publication trail in the .swarm events store (pr_feedback_publication_*, pr_feedback_push_attempt_*, pr_feedback_published)"),lines.join(`
|
|
1307
1307
|
`)}function findDanglingLivePublicationGeneration(directory,sessionID){let text;try{text=readCoreEvents(directory).text}catch{return null}if(!text.trim())return null;let dangling=null;for(let line of text.split(`
|
|
1308
1308
|
`)){if(!line.trim())continue;let event;try{event=JSON.parse(line)}catch{continue}if(typeof event.type!=="string"||!PUBLICATION_EVENT_TYPES.has(event.type)||event.sessionID!==sessionID)continue;let generation=typeof event.generation==="number"?event.generation:null;switch(event.type){case"pr_feedback_publication_armed":case"pr_feedback_push_attempt_started":dangling=generation?{generation}:dangling;break;case"pr_feedback_publication_migrated":if(event.outcome==="armed")dangling=generation?{generation}:dangling;else dangling=null;break;default:dangling=null;break}}return dangling}function supersedeLivePublicationInPendingState(pending,reason){let publication=pending.prFeedbackPublication,active=publication?.active;if(!(pending.prFeedbackReadyToPublish!=null||active?.state==="armed"||active?.state==="push_in_flight"))return{state:pending,invalidationEvent:null};let now=isoNow(),attempts=(publication?.attempts??[]).map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"uncertain",exitStatus:"not-observed",diagnostic:`finalized by publication invalidation (${reason})`,postPush:{localHead:null,observedRemoteHead:null},completedAt:now}}),invalidatedActive=active?{...active,state:"invalidated",invalidatedAt:now,invalidationReason:reason}:void 0,nextState={...pending,updatedAt:now,prFeedbackReadyToPublish:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackPublication:active?nextPublicationContainer(publication,invalidatedActive,[],attempts):pending.prFeedbackPublication},invalidationEvent=active?{type:"pr_feedback_publication_invalidated",sessionID:pending.sessionID,generation:active.generation,reason,previousState:active.state,drift:null,revisionDigest:active.revisionDigest,localHead:active.localHead,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,supersededBatchIds:active.evidence.batches.map((b)=>b.batchId)}:null;return{state:nextState,invalidationEvent}}function parseExactBoundPushIntent(command,armed){if(hasUnsafeShellControlSyntax(command))return{ok:!1,reason:"shell-syntax"};if(!armed.remoteBranchRef.startsWith("refs/heads/"))return{ok:!1,reason:"unbound-target"};let tokens2=command.trim().split(/\s+/);if(tokens2.length!==4||tokens2[0].toLowerCase()!=="git"||tokens2[1].toLowerCase()!=="push"||tokens2.some((token)=>/["'\\]/.test(token)))return{ok:!1,reason:"token-shape"};let[remoteToken,refspecToken]=[tokens2[2],tokens2[3]];if(remoteToken.startsWith("-")||refspecToken.startsWith("-"))return{ok:!1,reason:"flag-or-option"};if(/[:@]/.test(remoteToken)||remoteToken.includes("://"))return{ok:!1,reason:"credential-bearing-remote"};let refspecParts=refspecToken.split(":");if(refspecParts.length!==2)return{ok:!1,reason:refspecParts.length>2?"token-shape":"invalid-dest-ref"};let[sourceToken,destToken]=refspecParts;if(!destToken.startsWith("refs/heads/")||destToken==="refs/heads/")return{ok:!1,reason:"invalid-dest-ref"};if(sourceToken==="")return{ok:!1,reason:"delete-refspec"};if(sourceToken.includes("*")||destToken.includes("*"))return{ok:!1,reason:"wildcard-refspec"};if(remoteToken!==armed.remoteName)return{ok:!1,reason:"remote-mismatch"};if(sourceToken!==armed.localHead)return{ok:!1,reason:"source-mismatch"};if(destToken!==armed.remoteBranchRef)return{ok:!1,reason:"branch-mismatch"};let intent={remote:remoteToken,sourceSha:sourceToken,destRef:destToken};return{ok:!0,intent,digest:createHash53("sha256").update(JSON.stringify(intent),"utf8").digest("hex")}}async function admitPrFeedbackPushAttempt(directory,sessionID,callID,intent,intentDigest){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),active=state2?.prFeedbackPublication?.active;if(!state2||state2.mode!=="PR_FEEDBACK"||!active)throw Error("BLOCKED: PR_FEEDBACK push admission requires an armed publication generation");if(active.state!=="armed")throw Error(`BLOCKED: PR_FEEDBACK push admission requires the armed state, not ${active.state}`);let check3=await checkPublicationIdentity(directory,state2,active);if(check3.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check3.component}" (${check3.detail}); the push was not admitted`);if(check3.kind==="drift"){let invalidation=await applyPublicationInvalidationWhileLocked(directory,state2,`drift:${check3.component}`,{drift:check3});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check3.component}: ${check3.detail}). Rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow.`)}let now=isoNow();if(intent.remote!==active.remoteName||intent.sourceSha!==active.localHead||intent.destRef!==active.remoteBranchRef)throw Error("BLOCKED: PR_FEEDBACK push intent does not match the armed publication generation under the state lock; the push was not admitted");let observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),worktreeClean=await _test_exports2.resolveIsWorkingTreeCleanAsync(directory),baseAttempt={attemptId:randomUUID17(),generation:active.generation,sessionID:state2.sessionID,callID,intentDigest,intent:{remote:intent.remote,sourceSha:intent.sourceSha,destRef:intent.destRef},prePush:{localHead:active.localHead,worktreeClean:worktreeClean===!0,remoteName:active.remoteName,remoteBranchRef:active.remoteBranchRef,observedRemoteHead},startedAt:now};if(observedRemoteHead?.toLowerCase()===active.localHead.toLowerCase()){let attempt={...baseAttempt,result:{outcome:"completed",exitStatus:"not-observed",diagnostic:"remote branch already observed at the approved head (no-op push)",postPush:{localHead:localHead??null,observedRemoteHead:observedRemoteHead??null},completedAt:now}},nextState2={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,active,[],[...state2.prFeedbackPublication?.attempts??[],attempt])};await writeStateWhileLocked(directory,nextState2),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome:"completed",by:"no-op-observation",observedRemoteHead});return}let nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state2.prFeedbackPublication,{...active,state:"push_in_flight"},[],[...state2.prFeedbackPublication?.attempts??[],baseAttempt])};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_started",sessionID:state2.sessionID,generation:active.generation,intentDigest,intent,observedRemoteHead})});let attempts=(await readPrWorkflowGateState(directory,normalizedSessionID))?.prFeedbackPublication?.attempts??[];return attempts[attempts.length-1]?.result?.outcome==="completed"?{kind:"already-published-remotely"}:{kind:"started"}}function describeToolOutputText(output){if(typeof output==="string")return output;if(output&&typeof output==="object"&&"output"in output&&typeof output.output==="string")return output.output;try{return JSON.stringify(output)??""}catch{return""}}async function recordPrFeedbackPushAttemptResult(directory,input,command,output){let normalizedTool=(normalizeToolName(input.tool)??input.tool).toLowerCase();if(normalizedTool!=="bash"&&normalizedTool!=="shell")return;if(!/^\s*git\s+push/i.test(command))return;let normalizedSessionID=normalizeSessionID(input.sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active||active.state!=="push_in_flight"||!input.callID)return;let attemptIndex=publication.attempts.findIndex((attempt)=>!attempt.result&&attempt.callID===input.callID);if(attemptIndex<0)return;let now=isoNow(),localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef),remoteVerifiedAtApprovedHead=observedRemoteHead?.toLowerCase()===active.localHead.toLowerCase(),metadataExit=output?.metadata?.exitCode,exitStatus=typeof metadataExit==="number"&&Number.isInteger(metadataExit)?metadataExit:"not-observed",outcome;if(remoteVerifiedAtApprovedHead)outcome="completed";else if(exitStatus!=="not-observed"&&exitStatus!==0)outcome="rejected";else outcome="uncertain";let diagnostic=boundPublicationDiagnostic(remoteVerifiedAtApprovedHead?`push result observed; remote branch verified at the approved head${exitStatus!=="not-observed"&&exitStatus!==0?` (shell reported nonzero exit ${exitStatus}; the verified remote head is the publication truth)`:""}`:`push result observed without remote verification at the approved head; exit status ${exitStatus==="not-observed"?"not observed":exitStatus}; output: ${describeToolOutputText(output)}`),attempts=publication.attempts.map((attempt,index)=>index===attemptIndex?{...attempt,result:{outcome,exitStatus,diagnostic,postPush:{localHead:localHead??null,observedRemoteHead:observedRemoteHead??null},completedAt:now}}:attempt),nextState={...state2,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state2.sessionID,generation:active.generation,outcome,exitStatus,by:"tool-after",observedRemoteHead})})}async function cancelPrFeedbackPublication(directory,sessionID,reason){let normalizedSessionID=normalizeSessionID(sessionID),nextRevision=null,observedRemoteHead=null,cancelledGeneration=null,cancelledAttemptsFinalized=0;try{await withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state2?.prFeedbackPublication,active=publication?.active;if(!state2||!publication||!active)return;if(active.state==="cancelled_without_publication"){nextRevision=state2.revision;return}if(active.state!=="armed"&&active.state!=="push_in_flight"&&active.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK publication generation ${active.generation} is ${active.state}; only armed, push_in_flight, or invalidated generations may be cancelled`);let now=isoNow();observedRemoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,active.remoteName,active.remoteBranchRef);let attempts=publication.attempts.map((attempt)=>attempt.result?attempt:{...attempt,result:{outcome:"cancelled",exitStatus:"not-observed",diagnostic:"finalized by publication cancellation",postPush:{localHead:null,observedRemoteHead},completedAt:now}}),cancelled={...active,state:"cancelled_without_publication",cancelledAt:now,invalidationReason:active.invalidationReason??`cancelled:${reason}`},nextState={...state2,updatedAt:now,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(publication,cancelled,[],attempts)};nextRevision=(await writeStateWhileLocked(directory,nextState)).revision,cancelledGeneration=active.generation,cancelledAttemptsFinalized=attempts.filter((attempt)=>attempt.result?.outcome==="cancelled").length})}catch(error93){if(error93 instanceof Error&&error93.message.startsWith("BLOCKED: PR_FEEDBACK publication generation"))throw error93}return appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:normalizedSessionID,...cancelledGeneration!==null?{generation:cancelledGeneration}:{},reason,...cancelledAttemptsFinalized>0?{attemptsFinalized:cancelledAttemptsFinalized}:{},observedRemoteHead}),{revision:nextRevision,observedRemoteHead}}async function assertPrFeedbackPublicationArmed(directory,sessionID,options={}){let state2=await ensurePublicationGenerationCurrent(directory,sessionID)??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");state2=await reconcileForeignInFlightAttempt(directory,sessionID,options.currentCallId)??state2??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");let active=state2.prFeedbackPublication?.active;if(!active||active.state!=="armed"&&active.state!=="push_in_flight"){if(active?.state==="invalidated")throw Error(`BLOCKED: PR_FEEDBACK publication generation ${active.generation} was invalidated${active.invalidationReason?` (${active.invalidationReason})`:""}; rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow`);throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes")}let check3=await checkPublicationIdentity(directory,state2,active);if(check3.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check3.component}" (${check3.detail}); the armed window is unchanged and fails closed. Resolve the verification failure and retry.`);if(check3.kind==="drift"){let invalidation=await invalidatePublicationGeneration(directory,sessionID,`drift:${check3.component}`,{drift:check3,driftReverification:!0});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check3.component}: ${check3.detail}). Every approval of that generation is now superseded. Rerun Stage A and every independent gate, then arm a fresh generation with complete_pr_workflow.`)}return state2}async function resolvePrReviewWriterRunId(directory,sessionID,requestedRunId){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW"),workflowInstanceId=workflowIdentity(state2),normalizedRequested=requestedRunId?.trim()||void 0,stateBoundValues=[state2.prReviewReservedRunId,state2.prReviewTriggerEvalRunId,state2.prReviewArtifactRunId].filter((value)=>Boolean(value?.trim())),stateDistinct=[...new Set(stateBoundValues)];if(normalizedRequested&&stateDistinct.some((value)=>value!==normalizedRequested)){if(stateDistinct.length===1)throw Error(`BLOCKED: field run_id expected "${stateDistinct[0]}", got "${normalizedRequested}"`);throw Error(`BLOCKED: field run_id expected one unambiguous active value, got "${normalizedRequested}" while active bindings are ${stateDistinct.join(", ")}`)}let recoveredReservations=normalizedRequested?[]:await findOwnedPrReviewRunReservations(directory,normalizedSessionID,workflowInstanceId),distinct=[...new Set([...stateBoundValues,...recoveredReservations])];if(!normalizedRequested&&distinct.length>1)throw Error(`BLOCKED: field run_id expected one unambiguous active value, got (omitted) while active bindings are ${distinct.join(", ")}`);let reserve=async(runId)=>{return await tryCreatePrReviewRunReservation(directory,normalizedSessionID,workflowInstanceId,runId)==="occupied"?null:runId},resolvedRunId=normalizedRequested??distinct[0];if(!resolvedRunId){let base=generatePrReviewRunId();for(let suffix=0;suffix<MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS&&!resolvedRunId;suffix+=1){let candidate=suffix===0?base:`${base}-${suffix}`,reserved=await reserve(candidate);if(reserved)resolvedRunId=reserved}if(!resolvedRunId)throw Error(`BLOCKED: PR_REVIEW run_id generation exhausted ${MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS} reservation attempts for base "${base}"`)}else if(await reserve(resolvedRunId)===null)throw Error(`BLOCKED: field run_id expected an unused active reservation, got "${resolvedRunId}" which is already occupied by another workflow`);if(state2.prReviewReservedRunId===resolvedRunId)return resolvedRunId;let nextState={...state2,updatedAt:isoNow(),prReviewReservedRunId:resolvedRunId};return(await writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:state2.workflowInstanceId})).prReviewReservedRunId??resolvedRunId}))}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,runId,artifactPath){let state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state,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(state2.prReviewTriggerEvalRunId&&state2.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state2.prReviewTriggerEvalRunId}"`);if(state2.prReviewArtifactRunId&&state2.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state2.prReviewArtifactRunId}"`);let nextState={...state2,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await persistState2(directory,nextState),nextState}async function bindPrReviewTriggerLedger(directory,sessionID,input){let ledger;try{ledger=validatePrReviewInlineTriggerLedger(input)}catch(error93){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error93 instanceof Error?error93.message:String(error93)}`)}let state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;if(state2.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state2.prReviewTriggerLedger)}catch(error93){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state2}let nextState={...state2,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState2(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds,options={}){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),baseOnlyExplorerCheckpoint=boundary==="post_explorer"&&!state2.prReviewTriggerEvalPath;if(!state2.prReviewTriggerEvalPath&&!baseOnlyExplorerCheckpoint)throw Error("BLOCKED: PR_REVIEW findings persistence requires the trigger evaluation artifact (write_pr_review_trigger_eval must complete first)");if(baseOnlyExplorerCheckpoint&&!options.skipBaseCoverage)state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;let persistedBoundaries=state2.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 createPrReviewGateContext2(directory,state2);if(boundary==="post_reviewer")state2=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state2=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state2.prReviewArtifactRunId&&state2.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state2.prReviewArtifactRunId}"`);if(state2.prReviewTriggerEvalRunId&&state2.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state2.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory2(directory,state2,ctx),normalizedFindingIds=[...new Set(findingIds)].sort();if(normalizedFindingIds.length!==findingIds.length||JSON.stringify(normalizedFindingIds)!==JSON.stringify([...expectedFindingIds].sort())){let actualSet=new Set(normalizedFindingIds),expectedSet=new Set(expectedFindingIds),missing=[...expectedSet].filter((id)=>!actualSet.has(id)),extra=[...actualSet].filter((id)=>!expectedSet.has(id)),duplicates=[...new Set(findingIds.filter((id,index)=>findingIds.indexOf(id)!==index))].sort();throw Error(`BLOCKED: PR_REVIEW ${boundary} findings must exactly cover the discovered candidate inventory; missing: ${missing.join(", ")||"(none)"}; extra: ${extra.join(", ")||"(none)"}; duplicates: ${duplicates.join(", ")||"(none)"}`)}return state2}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),violations=[],report=(findingId2,field,expected,actual)=>{violations.push({findingId:findingId2,detail:`${field} expected ${expected}, got ${actual}`})},reportSeverity=(record3,expected)=>{if(record3.severity===expected)return;let raw=record3.severity,actual=raw===void 0?"(omitted)":raw===null?"(null)":raw===""?"(empty)":`"${raw}"`;report(record3.finding_id,"severity",`"${expected}"`,actual)},reportRiskMetadata=(record3,reviewer)=>{if(record3.status!=="CONFIRMED")return;let expectedImpact=reviewer.riskImpact??"UNKNOWN",expectedTags=reviewer.riskTags??[],actualImpact=record3.risk_impact??"UNKNOWN",actualTags=record3.risk_tags??[];if(actualImpact!==expectedImpact)report(record3.finding_id,"risk_impact",`"${expectedImpact}"`,record3.risk_impact===void 0?"(omitted)":`"${actualImpact}"`);if(actualTags.join(",")!==expectedTags.join(","))report(record3.finding_id,"risk_tags",JSON.stringify(expectedTags),record3.risk_tags===void 0?"(omitted)":JSON.stringify(actualTags))};if(boundary==="post_explorer"){let candidateSeverities=derivePrReviewCandidateSeverities(directory,state2,await createPrReviewGateContext2(directory,state2));for(let record3 of records){if(record3.status!=="PENDING")report(record3.finding_id,"status",'"PENDING"',`"${record3.status}"`);if(record3.next_action!=="route_to_reviewer")report(record3.finding_id,"next_action",'"route_to_reviewer"',`"${record3.next_action}"`);let candidateSeverity=candidateSeverities.get(record3.finding_id);if(candidateSeverity){reportSeverity(record3,candidateSeverity);continue}if(record3.finding_id===PR_REVIEW_CLEAN_SENTINEL_ID){reportSeverity(record3,"NONE");continue}violations.push({findingId:record3.finding_id,detail:"no authoritative candidate severity (absent from the derived candidate inventory)"})}}else{let ctx=await createPrReviewGateContext2(directory,state2),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state2,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state2,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):void 0;for(let record3 of records){let reviewer=reviewerVerdicts.get(record3.finding_id);if(!reviewer){violations.push({findingId:record3.finding_id,detail:"no authoritative reviewer verdict (absent from the settled reviewer map)"});continue}let requiresCritic=prReviewFindingRequiresCritic({classification:reviewer.classification,severity:reviewer.severity,risk_impact:reviewer.riskImpact,risk_tags:reviewer.riskTags}),expectedStatus=reviewer.classification==="UNVERIFIED"?"PENDING":reviewer.classification;if(boundary==="post_reviewer"){if(record3.status!==expectedStatus)report(record3.finding_id,"status",`"${expectedStatus}"`,`"${record3.status}"`);let expectedAction=requiresCritic?"route_to_critic":reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record3.next_action!==expectedAction)report(record3.finding_id,"next_action",`"${expectedAction}"`,`"${record3.next_action}"`);reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer);continue}if(!requiresCritic){let expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record3.status!==expectedStatus)report(record3.finding_id,"status",`"${expectedStatus}"`,`"${record3.status}"`);if(record3.next_action!==expectedAction)report(record3.finding_id,"next_action",`"${expectedAction}"`,`"${record3.next_action}"`);reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer);continue}let critic=criticVerdicts?.get(record3.finding_id);if(!critic){reportSeverity(record3,reviewer.severity),reportRiskMetadata(record3,reviewer),violations.push({findingId:record3.finding_id,detail:"no authoritative critic verdict (absent from the settled critic map)"});continue}if(critic.status==="DISPROVED"){if(record3.status!=="DISPROVED")report(record3.finding_id,"status",'"DISPROVED"',`"${record3.status}"`);if(record3.next_action!=="suppress_with_reason")report(record3.finding_id,"next_action",'"suppress_with_reason"',`"${record3.next_action}"`)}else{if(record3.status!=="CONFIRMED")report(record3.finding_id,"status",'"CONFIRMED"',`"${record3.status}"`);if(!["report","handoff_to_feedback"].includes(record3.next_action))report(record3.finding_id,"next_action",'"report" or "handoff_to_feedback"',`"${record3.next_action}"`)}reportSeverity(record3,critic.severity)}}if(violations.length>0){violations.sort((left,right)=>left.findingId<right.findingId?-1:left.findingId>right.findingId?1:0);let lines=violations.map((violation)=>` ${violation.findingId}: ${violation.detail}`);throw Error(`BLOCKED: PR_REVIEW ${boundary} artifact invalid — ${violations.length} violation(s):
|
|
1309
1309
|
${lines.join(`
|
|
1310
1310
|
`)}`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state2=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state2.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state2,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState2(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW");if(state2.prReviewArtifactRunId!==runId||!(state2.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let read=await readPrReviewFeedbackHandoffArtifact(directory,artifactPath),command=`/swarm pr-feedback ${read.artifact.pr_url} continue from .swarm/${artifactPath}`,consentInput={sessionID:normalizedSessionID,runId,handoffPath:artifactPath,handoffDigest:read.digest,prUrl:read.artifact.pr_url,prHeadSha:read.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(read.artifact.finding_ids),sourceWorkflowInstanceId:workflowIdentity(state2)},existing=await readPrReviewFeedbackConsent(directory,runId),alreadyOffered=existing!==null;if(existing)assertMatchingPrReviewFeedbackConsent(existing,consentInput);else await writePrReviewFeedbackConsent(directory,{schema_version:1,state:"offered",session_id:normalizedSessionID,source_workflow_instance_id:workflowIdentity(state2),run_id:runId,handoff_path:artifactPath,handoff_digest:read.digest,pr_url:read.artifact.pr_url,pr_head_sha:read.artifact.pr_head_sha.toLowerCase(),finding_ids_digest:consentInput.findingIdsDigest,confirmation_command:command,offered_at:isoNow()});if(alreadyOffered&&state2.prReviewHandoffPath===artifactPath)return{state:state2,alreadyOffered:!0};let nextState={...state2,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return{state:await writeStateWhileLocked(directory,nextState),alreadyOffered}}))}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative27=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative27.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative27}}function buildAcceptedPrFeedbackContinuationCommands(confirmationCommand,relativeHandoffPath,requestedPrUrl){let commands=new Set([confirmationCommand]);if(!requestedPrUrl)commands.add(`/swarm pr-feedback continue from .swarm/${relativeHandoffPath}`);return commands}async function readBoundedSwarmRegularFile2(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path106.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp8.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp8.lstat(absPath,{bigint:!0})}catch(error93){if(error93.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error93}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([fsp8.realpath(swarmRoot),fsp8.realpath(absPath)]),relativeRealPath=path106.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path106.sep}`)||path106.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports2.beforeBoundedSwarmFileOpen?.();let handle=await fsp8.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([fsp8.lstat(swarmRoot,{bigint:!0}),fsp8.lstat(absPath,{bigint:!0}),fsp8.realpath(swarmRoot),fsp8.realpath(absPath)]),postRelativeRealPath=path106.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(`..${path106.sep}`)||path106.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 prReviewRunReservationRelativePath(runId){return`pr-review/${runId}/run-reservation.json`}function prReviewFeedbackConsentRelativePath(runId){return`pr-review/${runId}/feedback-consent.json`}async function findOwnedPrReviewRunReservations(directory,sessionID,workflowInstanceId){let reviewRoot=validateSwarmPath(directory,"pr-review"),entries;try{entries=await fsp8.readdir(reviewRoot,{withFileTypes:!0})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}if(entries.length>MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES)throw Error(`BLOCKED: PR_REVIEW reservation recovery expected at most ${MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES} run entries, got ${entries.length}`);let owned=[];for(let entry of entries){if(!entry.isDirectory()||!PrReviewRunIdSchema.safeParse(entry.name).success)continue;let reservation;try{reservation=await readPrReviewRunReservation(directory,entry.name)}catch{continue}if(reservation?.session_id===sessionID&&reservation.workflow_instance_id===workflowInstanceId&&reservation.run_id===entry.name)owned.push(entry.name)}return owned.sort()}function hashPrReviewFindingIds(ids){return createHash53("sha256").update([...new Set(ids)].sort().join("\x00"),"utf8").digest("hex")}async function readPrReviewRunReservation(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewRunReservationRelativePath(runId),PR_REVIEW_RUN_RESERVATION_MAX_BYTES,"PR_REVIEW run reservation"),parsed=PrReviewRunReservationSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW run reservation is invalid");return parsed.data}catch(error93){if((error93 instanceof Error?error93.message:String(error93)).includes("does not exist"))return null;throw error93}}async function tryCreatePrReviewRunReservation(directory,sessionID,workflowInstanceId,runId){let relativePath=prReviewRunReservationRelativePath(runId),absolutePath=validateSwarmPath(directory,relativePath),runDirectory=path106.dirname(absolutePath),payload=`${JSON.stringify({schema_version:1,session_id:sessionID,workflow_instance_id:workflowInstanceId,run_id:runId,reserved_at:isoNow()},null,2)}
|
|
1311
1311
|
`;await fsp8.mkdir(runDirectory,{recursive:!0});try{return await fsp8.writeFile(absolutePath,payload,{encoding:"utf8",flag:"wx"}),"created"}catch(error93){if(error93.code!=="EEXIST")throw error93}let existing=await readPrReviewRunReservation(directory,runId);if(existing?.session_id===sessionID&&existing.workflow_instance_id===workflowInstanceId&&existing.run_id===runId)return"owned";let occupiedNames=new Set(["trigger-eval.json","findings.jsonl","feedback-handoff.json","feedback-consent.json"]);try{if((await fsp8.readdir(runDirectory)).some((entry)=>occupiedNames.has(entry)))return"occupied"}catch(error93){if(error93.code!=="ENOENT")throw error93}return"occupied"}async function readPrReviewFeedbackConsent(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewFeedbackConsentRelativePath(runId),PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES,"PR_REVIEW feedback consent artifact"),parsed=PrReviewFeedbackConsentSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback consent artifact is invalid");return parsed.data}catch(error93){if((error93 instanceof Error?error93.message:String(error93)).includes("does not exist"))return null;throw error93}}async function writePrReviewFeedbackConsent(directory,record3){let relativePath=prReviewFeedbackConsentRelativePath(record3.run_id),absolutePath=validateSwarmPath(directory,relativePath);if(record3.state==="confirmed"){await writeAtomicJson2(directory,absolutePath,record3);return}let parent=path106.dirname(absolutePath),tempPath=path106.join(parent,`.feedback-consent.${randomUUID17()}.tmp`);await fsp8.mkdir(parent,{recursive:!0});try{await fsp8.writeFile(tempPath,`${JSON.stringify(record3,null,2)}
|
|
1312
|
-
`,{encoding:"utf8",flag:"wx"}),await fsp8.link(tempPath,absolutePath)}finally{await fsp8.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(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:createHash53("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state2,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state2.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(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 deriveFeedbackHandoffFindingIds([...latest.values()])}async function readAuthoritativeFindingPolicy(directory,state2){let runId=state2.prReviewArtifactRunId;if(!runId||!state2.prReviewFindingsPath||!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW terminal finding policy evidence is not bound to the active run");let outcome=await readReviewOutcome({projectRoot:directory,sessionId:state2.sessionID,taskId:runId}).catch((error93)=>{throw Error(`BLOCKED: PR_REVIEW finding-policy evidence is missing or invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}),routeReceipt=outcome.evidence.routeReceipt;if(!routeReceipt||typeof routeReceipt!=="object")throw Error("BLOCKED: PR_REVIEW finding-policy evidence has no route receipt");let receipt=routeReceipt,expectedPath=`pr-review/${runId}/findings.jsonl`,raw=await readBoundedSwarmRegularFile2(directory,state2.prReviewFindingsPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),findingsDigest=createHash53("sha256").update(raw,"utf8").digest("hex");if(receipt.kind!=="pr_review_finding_policy"||receipt.version!==FINDING_POLICY_VERSION||receipt.sessionId!==state2.sessionID||receipt.taskId!==runId||receipt.boundary!=="post_critic"||receipt.prHeadSha!==state2.prHeadSha||receipt.findingsPath!==expectedPath||receipt.findingsDigest!==findingsDigest)throw Error("BLOCKED: PR_REVIEW finding-policy route receipt is stale or does not bind the final findings artifact");let synthesis=PrReviewFindingPolicySynthesisSchema.safeParse(outcome.evidence.synthesis);if(!synthesis.success)throw Error("BLOCKED: PR_REVIEW finding-policy synthesis is invalid or incomplete");return{policyFindings:synthesis.data.findings,criticSettlements:synthesis.data.criticSettlements??[]}}async function readPrReviewFinalFindingPolicyForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),findings=(await readAuthoritativeFindingPolicy(directory,state2)).policyFindings,permittedVerdicts=allowedPrReviewReportVerdicts(settlement.kind,findings),policyProjection=evaluateFinalFindingPolicy({policyVersion:FINDING_POLICY_VERSION,finalStatus:"COMPLETE",coverage:settlement.kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:settlement.kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings}),sourceIdsByPolicyFindingId=new Map(findings.map((finding)=>[finding.id,Array.isArray(finding.sourceFindingIds)?finding.sourceFindingIds.filter((value)=>typeof value==="string"):[]])),blockingFindingIds=policyProjection.blockingFindingIds.flatMap((id)=>sourceIdsByPolicyFindingId.get(id)??[id]).sort();return{policyVersion:1,permittedVerdicts,blockingFindingIds}}function canonicalGitHubPrUrl(value){try{let url3=new URL(value);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com")return null;let matched=url3.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 assertMatchingPrReviewFeedbackConsent(record3,input){if(record3.session_id!==input.sessionID||record3.run_id!==input.runId||record3.handoff_path!==input.handoffPath||record3.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record3.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record3.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record3.finding_ids_digest!==input.findingIdsDigest||record3.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state2){return state2.workflowInstanceId??`legacy-${createHash53("sha256").update(`${state2.sessionID}\x00${state2.mode}\x00${state2.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(state2,relativePath,read,requestedPrUrl){let existing=state2.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state2.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 "${state2.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: PR_REVIEW transition refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before transitioning.`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state2),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"completePrWorkflow critic-coverage gate"),authoritativeCriticSettlements=[];if(criticInventory.length>0){if(!(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);authoritativeCriticSettlements=deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory),await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx);let criticVerdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),reviewerClaims=authoritativeReviewerClaims2(directory,state2,ctx),settledReceipts=[];for(let[itemId,verdict]of criticVerdicts){if(verdict.status!=="UPHELD"&&verdict.status!=="DOWNGRADED"&&verdict.status!=="DISPROVED")continue;let reviewerRowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!reviewerRowDigest)continue;settledReceipts.push({findingId:itemId,status:verdict.status,reviewerRowDigest})}if(reducePrReviewEvent(state2,{type:"critic_result_recorded",criticRequiredFindingIds:criticInventory,criticSettledReceipts:settledReceipts}).status==="rejected"){let settledIds=new Set(settledReceipts.map((r)=>r.findingId)),unfulfilled=criticInventory.filter((id)=>!settledIds.has(id));throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${unfulfilled.join(", ")}`)}}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state2.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state2.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state2.prReviewHandoffRequired&&!state2.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");let criticSettlementIncomplete=authoritativeCriticSettlements.some((settlement2)=>!settlement2.terminal),findingPolicyAuthority=criticSettlementIncomplete?null:await readAuthoritativeFindingPolicy(directory,state2);if(!criticSettlementIncomplete&&criticInventory.length>0){let persistedSettlements=findingPolicyAuthority?.criticSettlements??[],actualById=new Map(authoritativeCriticSettlements.map((settlement2)=>[settlement2.findingId,settlement2]));if(persistedSettlements.length!==authoritativeCriticSettlements.length||persistedSettlements.some((settlement2)=>{let actual=actualById.get(settlement2.findingId);return!actual||actual.terminal!==settlement2.terminal||actual.status!==settlement2.status}))throw Error("BLOCKED: PR_REVIEW finding-policy critic settlements are stale or do not match the authenticated critic verdict map")}let reviewerReceipts=(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer").map((batch)=>({id:batch.batchId,valid:!0})),councilEnabled=(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"),criticEnabled=criticInventory.length>0,policyReadiness=assessTerminalReadiness({baseReceipt:{id:"base-coverage-settlement",valid:Boolean((state2.prReviewBaseDispatches??[]).length>0||state2.prReviewBaseDispatch)},reviewerReceipts,criticReceipt:{id:"critic-coverage-settlement",valid:!criticEnabled||!criticSettlementIncomplete&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic")},coverage:{kind:"base",quality:settlement.kind==="COMPLETE"?"complete":"partial",provenance:"valid"},council:{enabled:councilEnabled,receipt:councilEnabled?{id:"council-settlement",valid:!0}:null},criticSettlements:criticEnabled?authoritativeCriticSettlements:void 0});if(!policyReadiness.ready)throw Error(`BLOCKED: PR_REVIEW terminal finding readiness is incomplete: ${policyReadiness.blockers.join(", ")}`);return{state:state2,settlement}}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,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;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),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(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");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}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 lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),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 state2=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state2),previous=state2.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 record3={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record3]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state2=await readPrWorkflowGateState(directory,sessionID);if(state2?.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state2)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state2)!==declaration.revisionDigest)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 consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prFeedbackScopes:(state2.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}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=[],callID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state2.mode==="PR_FEEDBACK"&&state2.prFeedbackReadyToPublish&&!state2.prFeedbackPublication)state2=await ensurePublicationGenerationCurrent(directory,sessionID)??state2;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.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(state2.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state2.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state2.prHeadSha,allowFetch:!state2.prHeadSha,allowTrackingFetch:Boolean(state2.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state2.mode),isTrustedWorkflowTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{}),isAllowlistedReadOnlyTool=normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool),readOnlyArgumentClassification=isAllowlistedReadOnlyTool?classifyReadOnlyToolArguments(normalizedTool,args2??{}):null,isNamedReadOnlyTool=isTrustedWorkflowTool||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0,isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0;if(state2.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state2.mode} requires manual Git recovery before controller work can continue. code=${state2.checkoutRecovery.code} retryable=false required_action=${state2.checkoutRecovery.requiredAction}`)}if(state2.mode==="PR_REVIEW"&&isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!1)throw Error(`BLOCKED: PR_REVIEW is read-only; tool "${normalizedTool}" rejected argument "${readOnlyArgumentClassification.path}": ${readOnlyArgumentClassification.constraint}`);if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state2.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool3&&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=isShellTool3&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state2.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state2.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state2.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(state2.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&&!isShellTool3&&!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(state2.mode));if(state2.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state2.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(state2.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)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,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state2.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state2.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(!state2.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(!state2.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 readPrReviewReentryBindingContext(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state2?prReviewReentryBindingFromState(directory,state2):null}async function prReviewReentryBindingFromState(directory,state2){if(state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2);return{prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state2.revision,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},...state2.prReviewArtifactRunId??state2.prReviewReservedRunId?{runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return!1;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return null;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state2=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state2.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options?.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${expectedMode} completion refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store and re-run completion (a healthy empty store still completes through its valid INCOMPLETE route).`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),dispatchCoverageFinalization=(finalizationSettlement)=>{let outcome=reducePrReviewEvent(state2,{type:"coverage_finalization_requested",settlement:{kind:finalizationSettlement.kind,coveredDimensions:finalizationSettlement.coveredDimensions,unresolvedDimensions:finalizationSettlement.unresolvedDimensions,liveDimensions:finalizationSettlement.liveDimensions},requestedVerdict:verdict});if(outcome.status==="applied")return;let{code}=outcome.rejection;if(code==="live_lane_blocks_coverage"){if(finalizationSettlement.kind==="NO_COVERAGE")throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}if(code==="no_coverage_requires_incomplete")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);let allowedList=allowedPrReviewReportVerdicts(finalizationSettlement.kind,[]).join(" | ");throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion allows report_verdict ${allowedList}; got "${verdict}". Partial coverage never approves and never claims a full review.`)};if(dispatchCoverageFinalization(settlement),settlement.kind==="NO_COVERAGE"){let noCoverageRunId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let preAllowed=allowedPrReviewReportVerdicts(settlement.kind,[]);if(!preAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion allows report_verdict ${preAllowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`);let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state2)||readyState.revision!==state2.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");dispatchCoverageFinalization(ready.settlement);let finalFindingAuthority=await readAuthoritativeFindingPolicy(directory,readyState),policyAllowed=allowedPrReviewReportVerdicts(ready.settlement.kind,finalFindingAuthority.policyFindings);if(!policyAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${ready.settlement.kind} completion allows report_verdict ${policyAllowed.join(" | ")}; got "${verdict}". Final finding policy and coverage do not permit this report.`)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}let localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");let commitCount=await _test_exports2.resolveCommitCountSinceAsync(directory,state2.prHeadSha,localHead);if(commitCount===0){if(localHead!==state2.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_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readLegacySettledFeedbackClassifications(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{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state2.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});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_exports2.resolveIsExactSingleChildCommitAsync(directory,state2.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_exports2.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_exports2.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");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.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`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state2.revision),"completed"}function noActiveGateError(sessionID){return 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:*".`)}async function requireAnyActiveState(directory,sessionID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)throw noActiveGateError(sessionID);return state2}async function requireBoundState2(directory,sessionID,expectedMode){let state2=await requireAnyActiveState(directory,sessionID);if(state2.mode!==expectedMode)throw wrongModeError(state2,expectedMode);if(!state2.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state2.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state2}function wrongModeError(state2,expectedMode){return Error(`BLOCKED: session "${state2.sessionID}" is active in ${state2.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){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);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 tokens2=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens2.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 tokens2.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 unsafeReadOnlyArgument(path107,constraint,value){return{safe:!1,path:path107||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function classifyReadOnlyToolArguments(toolName,value,key2="",path107="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path107,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.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 unsafeReadOnlyArgument(path107,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path107,"HTTP method/verb must be GET or HEAD for a read-only tool",value);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())?{safe:!0}:unsafeReadOnlyArgument(path107,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path107,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);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 unsafeReadOnlyArgument(path107,"query/request text contains a mutating operation",value);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)?unsafeReadOnlyArgument(path107,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key2,`${path107}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path107,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path107,"argument type is not supported by the read-only classifier",value)}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 tokens2=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens2.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!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==='"'){quoted2=!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=tokens2.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<tokens2.length;index+=1)if(tokens2[index].value==="--jq"&&tokens2[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 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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length!==3||tokens2[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens2,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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens2;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens2.length===3&&tokens2[0]==="branch"){let upstream=tokens2[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens2[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===0||tokens2[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="stash")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="worktree")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=command.trim().split(/\s+/);if(tokens2.length<4||tokens2[0]!=="gh"||tokens2[1]!=="pr"||tokens2[2]!=="checkout")return!1;let target=tokens2[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<tokens2.length;index+=1){let token=tokens2[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=tokens2[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens2[++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,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state2.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_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state2.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 assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory2(directory,state2,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state2.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state2.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful2=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;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state2.prReviewTriggerEvalPath)for(let batch of[...state2.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful2.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(state2.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state2.prReviewTriggerEvalPath),triggerArtifact;try{let triggerStat=statSync39(triggerPath);if(!triggerStat.isFile()||triggerStat.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error("trigger evaluation artifact exceeds its read bound");triggerArtifact=JSON.parse(readFileSync42(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error93){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}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=[],candidateSeverities=new Map,extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1,sourceRead=findByBatchIdDetailed(directory,source.batchId,{parentSessionId:state2.sessionID});if(sourceRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW discovery provenance cannot be read for ${source.workflowLane??source.laneId}: the delegation store is unreadable after ${sourceRead.attempts} attempts (${sourceRead.reason}); the lane's records are UNKNOWN, not absent. Restore the store and re-run discovery.`);for(let record3 of sourceRead.value){if(record3.laneId!==source.laneId||record3.mode!==source.mode||record3.workspace?.prHeadSha!==state2.prHeadSha||record3.workspace?.gitHead!==state2.prHeadSha)continue;let structured=record3.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record3.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state2,record3,source.mode,record3.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);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}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.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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 normalizeCandidateArtifactCached(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 issue3 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue3.field}: ${issue3.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state2,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state2,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state2,phase){let all=state2.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 reviewerSubagentSessionIds2(directory,state2){let forbidden=new Set(state2.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer")){let batchRead=findByBatchIdDetailed(directory,reviewerBatch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW critic reuse ban cannot be derived: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); reviewer batch ${reviewerBatch.batchId}'s child sessions are UNKNOWN, not absent. Restore the store and re-derive.`);for(let record3 of batchRead.value){let subagentSessionId=record3.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}}return forbidden}function batchMayContributeClaims2(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state2.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 successful2=successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.has(lane.workflowLane))}function authoritativeReviewerClaims2(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state2,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state2,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[reviewerItemBindingKey(itemId)]=rowDigest}return bindings}function derivePrReviewCriticInventory2(directory,state2,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state2,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"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 deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return criticInventory.map((findingId2)=>{let verdict=verdicts.get(findingId2);if(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE")return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"};if(verdict.status==="UPHELD"||verdict.status==="DOWNGRADED"||verdict.status==="DISPROVED")return{findingId:findingId2,terminal:!0,status:verdict.status};return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"}})}async function readAuthoritativePrReviewCriticSettlements(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),inventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"readAuthoritativePrReviewCriticSettlements");return deriveAuthoritativeCriticSettlements(directory,state2,ctx,inventory)}function deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx){return new Map([...authoritativeReviewerClaims2(directory,state2,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}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,state2,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state2,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state2,"critic",ctx),verdicts,origin),verdicts}async function readAuthoritativePrReviewCriticVerdicts(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return authoritativeCriticVerdictsForGate(directory,state2,ctx,"write_pr_review_artifact critic settlement")}function derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state2,"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 derivePrReviewCriticInventory2(directory,state2,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_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record3,result,expected}=args2;if(expected.checkWorkflowLane&&record3.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record3.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record3.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record3.ownedWorkflowLanes??(record3.workflowLane?[record3.workflowLane]:[]));if(record3.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record3.mode??"(missing)");if(record3.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record3.workspace?.prHeadSha??"(missing)");if(record3.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record3.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record3.status!=="completed")return failedLaneValidation("record.status","completed",record3.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!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((record3)=>record3.laneId&&expectedByLaneId.has(record3.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record3 of relevantRecords){let laneRecords=recordsByLaneId.get(record3.laneId)??[];laneRecords.push(record3),recordsByLaneId.set(record3.laneId,laneRecords);let sessionId=record3.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 record3=laneRecords[0],subagentSessionId=record3.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record3.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(record3.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record3.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record3,result:record3.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record3.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record3.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record3,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW batch integrity cannot be analyzed for ${batchId}: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Restore the store and re-validate.`);let records=batchRead.value,analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state2.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_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state2,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful2.add(obligation)}return successful2}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 validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record3,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!==record3.batchId)return failedLaneValidation("artifact.batch_id",record3.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record3.laneId)return failedLaneValidation("artifact.lane_id",record3.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record3.subagentSessionId)return failedLaneValidation("artifact.session_id",record3.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record3.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record3.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record3.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record3.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record3.normalizedAgent)return failedLaneValidation("artifact.role",record3.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record3.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record3.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&&record3.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record3.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 loadArtifactPassingLaneIntegrity2(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record3.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state2,record3,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record3.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state2,record3,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";return analyzeLegacyVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}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)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record3.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}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,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,cleanAttestationSalvaged=!1,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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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:acceptPartial,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);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");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)||Boolean(parsed.clean_attestation_salvaged)||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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};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,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion2(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,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return recordIntegrity;let structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt","missing structured receipt (legacy transcript adapter disabled)");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,input.result.transcriptIncomplete===!0)})),salvagedLanes=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");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,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state2=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state2.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state2.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state2.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state2.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state2.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims2(input.directory,state2,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzeLegacyVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state2.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!legacyFeedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state2.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{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}async function persistState2(directory,state2){let validated=PrWorkflowGateStateSchema.parse(state2);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state2,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}function boundSalvageDisclosure(sessionID,schemaErrors,coordinationNotice,revisionSalvageable=!0,armedShapeUnreadable=!1,publicationShapeUnreadable=!1){let disclosure=`DEGRADED: PR workflow gate state for session "${sessionID}" `+(coordinationNotice?`${coordinationNotice} and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). `:"failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). ")+`Schema errors: ${schemaErrors.join("; ")}.`+(revisionSalvageable?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":""),maxDisclosureChars=MAX_SALVAGED_SCHEMA_ERROR_CHARS*12;return disclosure.length<=maxDisclosureChars?disclosure:`${disclosure.slice(0,maxDisclosureChars-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")return{state:coordination.state,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationCorrupt=coordination.kind==="corrupt",coordinationGeneration=coordinationCorrupt?coordination.generation:void 0,coordinationReason=coordinationCorrupt?coordination.reason:void 0,filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(parsed.success){if(parsed.data.sessionID!==normalizedSessionID||coordinationGeneration!==void 0&&parsed.data.revision!==coordinationGeneration)throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(!coordinationCorrupt)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationSchemaError=boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`);return{state:parsed.data,salvaged:!0,schemaErrors:[coordinationSchemaError],disclosure:boundSalvageDisclosure(normalizedSessionID,[coordinationSchemaError],"coordination authority was corrupt and the valid shadow projection was used"),revisionSalvageable:!0,armedShapeUnreadable:!1}}let invalidError=Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(typeof parsedJson!=="object"||parsedJson===null||Array.isArray(parsedJson))throw invalidError;let rawRecord=parsedJson,salvagedSessionID=exports_external.string().min(1).safeParse(rawRecord.sessionID),salvagedMode=exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).safeParse(rawRecord.mode);if(!salvagedSessionID.success||!salvagedMode.success||salvagedSessionID.data!==normalizedSessionID)throw invalidError;let salvagedRevision=exports_external.number().int().nonnegative().safeParse(rawRecord.revision),salvagedHead=exports_external.string().min(1).safeParse(rawRecord.prHeadSha),salvagedActivatedAt=exports_external.string().min(1).safeParse(rawRecord.activatedAt),salvagedUpdatedAt=exports_external.string().min(1).safeParse(rawRecord.updatedAt);if(coordinationGeneration!==void 0&&(!salvagedRevision.success||salvagedRevision.data!==coordinationGeneration))throw invalidError;let armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,shadowSchemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue3)=>boundSalvagedSchemaError(`${issue3.path.join(".")||"(root)"}: ${issue3.message}`)),schemaErrors=[...coordinationCorrupt?[boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`)]:[],...shadowSchemaErrors].slice(0,MAX_SALVAGED_SCHEMA_ERRORS),disclosure=boundSalvageDisclosure(normalizedSessionID,schemaErrors,coordinationCorrupt?`coordination authority was corrupt (${coordinationReason}) and the shadow projection was used`:void 0,salvagedRevision.success,armedShapeUnreadable,publicationShapeUnreadable);return{state:{schemaVersion:GATE_SCHEMA_VERSION,revision:salvagedRevision.success?salvagedRevision.data:0,sessionID:salvagedSessionID.data,mode:salvagedMode.data,activatedAt:salvagedActivatedAt.success?salvagedActivatedAt.data:isoNow(),updatedAt:salvagedUpdatedAt.success?salvagedUpdatedAt.data:isoNow(),...salvagedHead.success?{prHeadSha:salvagedHead.data}:{},...salvagedArmed.success?{prFeedbackReadyToPublish:salvagedArmed.data}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}var 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,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,GATE_SCHEMA_VERSION=1,MAX_WORKFLOW_BATCHES=128,MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS=128,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS=240,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,MAX_DISCLOSED_LANE_IDS=10,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,CAS_ESCAPE_DISCLOSURE="state revision unsalvageable; cleared without compare-and-swap",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS=180000,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,DELEGATION_READ_UNCERTAIN_LOG_LIMIT=64,delegationReadUncertainLogged,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,PrReviewFindingPolicySynthesisFindingSchema,PrReviewCriticSettlementEvidenceSchema,PrReviewFindingPolicySynthesisSchema,_test_exports2,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,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,MAX_SALVAGED_SCHEMA_ERRORS=10,MAX_SALVAGED_SCHEMA_ERROR_CHARS=240;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_collection_receipt();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_finding_policy();init_legacy_transcript_adapter();init_persistence();init_reducer();init_scope_binding();init_state2();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();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};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,MAX_PR_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),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).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.optional()}).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(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).strict(),PrFeedbackInventoryAmendmentRecordSchema=exports_external.object({entry:exports_external.string().min(1),amendedAt:exports_external.string().min(1),batch:exports_external.number().int().positive()}).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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").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(),prReviewResilience:PrReviewResilienceStateRecordSchema.optional(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).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(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).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(),prFeedbackInventoryAmendments:exports_external.array(PrFeedbackInventoryAmendmentRecordSchema).max(MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS).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(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_WORKFLOW_STALE_LANE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES=new Set(["pending","running"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;delegationReadUncertainLogged=new Set;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;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"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);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(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).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(),PrReviewFindingPolicySynthesisFindingSchema=exports_external.object({id:exports_external.string().min(1).max(128),status:exports_external.string().min(1),severity:exports_external.string().min(1),action:exports_external.string().min(1)}).passthrough(),PrReviewCriticSettlementEvidenceSchema=exports_external.object({findingId:exports_external.string().min(1).max(128),terminal:exports_external.boolean(),status:exports_external.enum(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"])}).passthrough(),PrReviewFindingPolicySynthesisSchema=exports_external.object({findings:exports_external.array(PrReviewFindingPolicySynthesisFindingSchema),criticSettlements:exports_external.array(PrReviewCriticSettlementEvidenceSchema).optional()});bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),delegationReadUncertainLogged.clear(),_test_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforePrReviewReentryReservation=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return composePrReviewPhaseVerdicts(directory,state2,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCandidateInventory2(directory,state2,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp8.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});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(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","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 /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens2=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens2[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,cancellationRequested=tokens2.includes(CANCEL_PUBLICATION_FLAG),reasonStartIndex=knownMode?1:0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
1312
|
+
`,{encoding:"utf8",flag:"wx"}),await fsp8.link(tempPath,absolutePath)}finally{await fsp8.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(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:createHash53("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state2,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state2.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(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 deriveFeedbackHandoffFindingIds([...latest.values()])}async function readAuthoritativeFindingPolicy(directory,state2){let runId=state2.prReviewArtifactRunId;if(!runId||!state2.prReviewFindingsPath||!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW terminal finding policy evidence is not bound to the active run");let outcome=await readReviewOutcome({projectRoot:directory,sessionId:state2.sessionID,taskId:runId}).catch((error93)=>{throw Error(`BLOCKED: PR_REVIEW finding-policy evidence is missing or invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}),routeReceipt=outcome.evidence.routeReceipt;if(!routeReceipt||typeof routeReceipt!=="object")throw Error("BLOCKED: PR_REVIEW finding-policy evidence has no route receipt");let receipt=routeReceipt,expectedPath=`pr-review/${runId}/findings.jsonl`,raw=await readBoundedSwarmRegularFile2(directory,state2.prReviewFindingsPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),findingsDigest=createHash53("sha256").update(raw,"utf8").digest("hex");if(receipt.kind!=="pr_review_finding_policy"||receipt.version!==FINDING_POLICY_VERSION||receipt.sessionId!==state2.sessionID||receipt.taskId!==runId||receipt.boundary!=="post_critic"||receipt.prHeadSha!==state2.prHeadSha||receipt.findingsPath!==expectedPath||receipt.findingsDigest!==findingsDigest)throw Error("BLOCKED: PR_REVIEW finding-policy route receipt is stale or does not bind the final findings artifact");let synthesis=PrReviewFindingPolicySynthesisSchema.safeParse(outcome.evidence.synthesis);if(!synthesis.success)throw Error("BLOCKED: PR_REVIEW finding-policy synthesis is invalid or incomplete");return{policyFindings:synthesis.data.findings,criticSettlements:synthesis.data.criticSettlements??[]}}async function readPrReviewFinalFindingPolicyForReport(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state2||state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),findings=(await readAuthoritativeFindingPolicy(directory,state2)).policyFindings,permittedVerdicts=allowedPrReviewReportVerdicts(settlement.kind,findings),policyProjection=evaluateFinalFindingPolicy({policyVersion:FINDING_POLICY_VERSION,finalStatus:"COMPLETE",coverage:settlement.kind==="COMPLETE"?{kind:"base",quality:"complete",provenance:"valid"}:settlement.kind==="PARTIAL"?{kind:"base",quality:"partial",provenance:"valid"}:{kind:"base",quality:"none",provenance:"valid"},findings}),sourceIdsByPolicyFindingId=new Map(findings.map((finding)=>[finding.id,Array.isArray(finding.sourceFindingIds)?finding.sourceFindingIds.filter((value)=>typeof value==="string"):[]])),blockingFindingIds=policyProjection.blockingFindingIds.flatMap((id)=>sourceIdsByPolicyFindingId.get(id)??[id]).sort();return{policyVersion:1,permittedVerdicts,blockingFindingIds}}function canonicalGitHubPrUrl(value){try{let url3=new URL(value);if(url3.protocol!=="https:"||url3.hostname.toLowerCase()!=="github.com")return null;let matched=url3.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 assertMatchingPrReviewFeedbackConsent(record3,input){if(record3.session_id!==input.sessionID||record3.run_id!==input.runId||record3.handoff_path!==input.handoffPath||record3.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record3.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record3.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record3.finding_ids_digest!==input.findingIdsDigest||record3.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state2){return state2.workflowInstanceId??`legacy-${createHash53("sha256").update(`${state2.sessionID}\x00${state2.mode}\x00${state2.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(state2,relativePath,read,requestedPrUrl){let existing=state2.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state2.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 "${state2.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: PR_REVIEW transition refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store before transitioning.`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state2),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state2.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"completePrWorkflow critic-coverage gate"),authoritativeCriticSettlements=[];if(criticInventory.length>0){if(!(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);authoritativeCriticSettlements=deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory),await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx);let criticVerdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx),reviewerClaims=authoritativeReviewerClaims2(directory,state2,ctx),settledReceipts=[];for(let[itemId,verdict]of criticVerdicts){if(verdict.status!=="UPHELD"&&verdict.status!=="DOWNGRADED"&&verdict.status!=="DISPROVED")continue;let reviewerRowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!reviewerRowDigest)continue;settledReceipts.push({findingId:itemId,status:verdict.status,reviewerRowDigest})}if(reducePrReviewEvent(state2,{type:"critic_result_recorded",criticRequiredFindingIds:criticInventory,criticSettledReceipts:settledReceipts}).status==="rejected"){let settledIds=new Set(settledReceipts.map((r)=>r.findingId)),unfulfilled=criticInventory.filter((id)=>!settledIds.has(id));throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${unfulfilled.join(", ")}`)}}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state2.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state2.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state2.prReviewHandoffRequired&&!state2.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");let criticSettlementIncomplete=authoritativeCriticSettlements.some((settlement2)=>!settlement2.terminal),findingPolicyAuthority=criticSettlementIncomplete?null:await readAuthoritativeFindingPolicy(directory,state2);if(!criticSettlementIncomplete&&criticInventory.length>0){let persistedSettlements=findingPolicyAuthority?.criticSettlements??[],actualById=new Map(authoritativeCriticSettlements.map((settlement2)=>[settlement2.findingId,settlement2]));if(persistedSettlements.length!==authoritativeCriticSettlements.length||persistedSettlements.some((settlement2)=>{let actual=actualById.get(settlement2.findingId);return!actual||actual.terminal!==settlement2.terminal||actual.status!==settlement2.status}))throw Error("BLOCKED: PR_REVIEW finding-policy critic settlements are stale or do not match the authenticated critic verdict map")}let reviewerReceipts=(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer").map((batch)=>({id:batch.batchId,valid:!0})),councilEnabled=(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"),criticEnabled=criticInventory.length>0,policyReadiness=assessTerminalReadiness({baseReceipt:{id:"base-coverage-settlement",valid:Boolean((state2.prReviewBaseDispatches??[]).length>0||state2.prReviewBaseDispatch)},reviewerReceipts,criticReceipt:{id:"critic-coverage-settlement",valid:!criticEnabled||!criticSettlementIncomplete&&(state2.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic")},coverage:{kind:"base",quality:settlement.kind==="COMPLETE"?"complete":"partial",provenance:"valid"},council:{enabled:councilEnabled,receipt:councilEnabled?{id:"council-settlement",valid:!0}:null},criticSettlements:criticEnabled?authoritativeCriticSettlements:void 0});if(!policyReadiness.ready)throw Error(`BLOCKED: PR_REVIEW terminal finding readiness is incomplete: ${policyReadiness.blockers.join(", ")}`);return{state:state2,settlement}}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,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;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),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(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");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}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 lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),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 state2=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state2),previous=state2.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 record3={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record3]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state2=await readPrWorkflowGateState(directory,sessionID);if(state2?.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state2)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2||state2.mode!=="PR_FEEDBACK")return null;let declaration=(state2.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state2)!==declaration.revisionDigest)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 consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prFeedbackScopes:(state2.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}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=[],callID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state2.mode==="PR_FEEDBACK"&&state2.prFeedbackReadyToPublish&&!state2.prFeedbackPublication)state2=await ensurePublicationGenerationCurrent(directory,sessionID)??state2;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.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(state2.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state2.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state2.prHeadSha,allowFetch:!state2.prHeadSha,allowTrackingFetch:Boolean(state2.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state2.mode),isTrustedWorkflowTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{}),isAllowlistedReadOnlyTool=normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool),readOnlyArgumentClassification=isAllowlistedReadOnlyTool?classifyReadOnlyToolArguments(normalizedTool,args2??{}):null,isNamedReadOnlyTool=isTrustedWorkflowTool||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0,isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0;if(state2.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state2.mode} requires manual Git recovery before controller work can continue. code=${state2.checkoutRecovery.code} retryable=false required_action=${state2.checkoutRecovery.requiredAction}`)}if(state2.mode==="PR_REVIEW"&&isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!1)throw Error(`BLOCKED: PR_REVIEW is read-only; tool "${normalizedTool}" rejected argument "${readOnlyArgumentClassification.path}": ${readOnlyArgumentClassification.constraint}`);if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state2.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool3&&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=isShellTool3&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state2.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state2.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state2.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(state2.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&&!isShellTool3&&!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(state2.mode));if(state2.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state2.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(state2.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)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,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state2.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state2.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(!state2.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(!state2.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 readPrReviewReentryBindingContext(directory,sessionID){let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state2?prReviewReentryBindingFromState(directory,state2):null}async function prReviewReentryBindingFromState(directory,state2){if(state2.mode!=="PR_REVIEW"||!state2.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state2);return{prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state2.revision,...state2.workflowInstanceId?{workflowInstanceId:state2.workflowInstanceId}:{},...state2.prReviewArtifactRunId??state2.prReviewReservedRunId?{runId:state2.prReviewArtifactRunId??state2.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return!1;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state2=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state2)return null;let binding=await prReviewReentryBindingFromState(directory,state2);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state2=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state2.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state2.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state2.sessionID,options?.laneLiveness);if(laneSettlement.uncertainty)throw Error(`BLOCKED: ${expectedMode} completion refused while the delegation store is unreadable after ${laneSettlement.uncertainty.attempts} attempts (${laneSettlement.uncertainty.reason}); open lanes are UNKNOWN, not absent. Restore the store and re-run completion (a healthy empty store still completes through its valid INCOMPLETE route).`);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state2),settlement=derivePrReviewDimensionSettlement(directory,state2,ctx.revisionDigest),dispatchCoverageFinalization=(finalizationSettlement)=>{let outcome=reducePrReviewEvent(state2,{type:"coverage_finalization_requested",settlement:{kind:finalizationSettlement.kind,coveredDimensions:finalizationSettlement.coveredDimensions,unresolvedDimensions:finalizationSettlement.unresolvedDimensions,liveDimensions:finalizationSettlement.liveDimensions},requestedVerdict:verdict});if(outcome.status==="applied")return;let{code}=outcome.rejection;if(code==="live_lane_blocks_coverage"){if(finalizationSettlement.kind==="NO_COVERAGE")throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}if(code==="no_coverage_requires_incomplete")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);let allowedList=allowedPrReviewReportVerdicts(finalizationSettlement.kind,[]).join(" | ");throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion allows report_verdict ${allowedList}; got "${verdict}". Partial coverage never approves and never claims a full review.`)};if(dispatchCoverageFinalization(settlement),settlement.kind==="NO_COVERAGE"){let noCoverageRunId=state2.prReviewArtifactRunId??state2.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let preAllowed=allowedPrReviewReportVerdicts(settlement.kind,[]);if(!preAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion allows report_verdict ${preAllowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`);let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state2)||readyState.revision!==state2.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");dispatchCoverageFinalization(ready.settlement);let finalFindingAuthority=await readAuthoritativeFindingPolicy(directory,readyState),policyAllowed=allowedPrReviewReportVerdicts(ready.settlement.kind,finalFindingAuthority.policyFindings);if(!policyAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${ready.settlement.kind} completion allows report_verdict ${policyAllowed.join(" | ")}; got "${verdict}". Final finding policy and coverage do not permit this report.`)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}let localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");let commitCount=await _test_exports2.resolveCommitCountSinceAsync(directory,state2.prHeadSha,localHead);if(commitCount===0){if(localHead!==state2.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_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readLegacySettledFeedbackClassifications(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{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state2.sessionID,prHeadSha:state2.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state2.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});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_exports2.resolveIsExactSingleChildCommitAsync(directory,state2.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_exports2.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_exports2.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");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.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`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state2.revision),"completed"}function noActiveGateError(sessionID){return 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:*".`)}async function requireAnyActiveState(directory,sessionID){let state2=await readPrWorkflowGateState(directory,sessionID);if(!state2)throw noActiveGateError(sessionID);return state2}async function requireBoundState2(directory,sessionID,expectedMode){let state2=await requireAnyActiveState(directory,sessionID);if(state2.mode!==expectedMode)throw wrongModeError(state2,expectedMode);if(!state2.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state2.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state2}function wrongModeError(state2,expectedMode){return Error(`BLOCKED: session "${state2.sessionID}" is active in ${state2.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){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);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 tokens2=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens2.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 tokens2.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 unsafeReadOnlyArgument(path107,constraint,value){return{safe:!1,path:path107||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function classifyReadOnlyToolArguments(toolName,value,key2="",path107="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path107,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.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 unsafeReadOnlyArgument(path107,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path107,"HTTP method/verb must be GET or HEAD for a read-only tool",value);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())?{safe:!0}:unsafeReadOnlyArgument(path107,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path107,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);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 unsafeReadOnlyArgument(path107,"query/request text contains a mutating operation",value);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)?unsafeReadOnlyArgument(path107,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key2,`${path107}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path107,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path107,"argument type is not supported by the read-only classifier",value)}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 tokens2=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens2.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!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==='"'){quoted2=!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=tokens2.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<tokens2.length;index+=1)if(tokens2[index].value==="--jq"&&tokens2[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 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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length!==3||tokens2[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens2,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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens2;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens2.length===3&&tokens2[0]==="branch"){let upstream=tokens2[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens2[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length===0||tokens2[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="stash")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=gitArgs.trim().split(/\s+/);if(tokens2.length<2||tokens2[0].toLowerCase()!=="worktree")return!1;if(tokens2[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens2.length;index+=1){let token=tokens2[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 tokens2=command.trim().split(/\s+/);if(tokens2.length<4||tokens2[0]!=="gh"||tokens2[1]!=="pr"||tokens2[2]!=="checkout")return!1;let target=tokens2[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<tokens2.length;index+=1){let token=tokens2[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=tokens2[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens2[++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,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state2.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_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state2){if(!state2.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state2.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state2.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 assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory2(directory,state2,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state2.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state2.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful2=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;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state2.prReviewTriggerEvalPath)for(let batch of[...state2.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful2.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(state2.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state2.prReviewTriggerEvalPath),triggerArtifact;try{let triggerStat=statSync39(triggerPath);if(!triggerStat.isFile()||triggerStat.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error("trigger evaluation artifact exceeds its read bound");triggerArtifact=JSON.parse(readFileSync42(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error93){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error93 instanceof Error?error93.message:String(error93)}`)}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=[],candidateSeverities=new Map,extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1,sourceRead=findByBatchIdDetailed(directory,source.batchId,{parentSessionId:state2.sessionID});if(sourceRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW discovery provenance cannot be read for ${source.workflowLane??source.laneId}: the delegation store is unreadable after ${sourceRead.attempts} attempts (${sourceRead.reason}); the lane's records are UNKNOWN, not absent. Restore the store and re-run discovery.`);for(let record3 of sourceRead.value){if(record3.laneId!==source.laneId||record3.mode!==source.mode||record3.workspace?.prHeadSha!==state2.prHeadSha||record3.workspace?.gitHead!==state2.prHeadSha)continue;let structured=record3.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record3.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record3.ownedWorkflowLanes?.length?record3.ownedWorkflowLanes:record3.workflowLane?[record3.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state2,record3,source.mode,record3.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);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}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.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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 normalizeCandidateArtifactCached(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 issue3 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue3.field}: ${issue3.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state2,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state2,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state2,phase){let all=state2.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 reviewerSubagentSessionIds2(directory,state2){let forbidden=new Set(state2.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state2.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer")){let batchRead=findByBatchIdDetailed(directory,reviewerBatch.batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW critic reuse ban cannot be derived: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); reviewer batch ${reviewerBatch.batchId}'s child sessions are UNKNOWN, not absent. Restore the store and re-derive.`);for(let record3 of batchRead.value){let subagentSessionId=record3.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}}return forbidden}function batchMayContributeClaims2(directory,state2,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state2.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 successful2=successfulObligationsFromExactBatch2(directory,state2,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.has(lane.workflowLane))}function authoritativeReviewerClaims2(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state2,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state2,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[reviewerItemBindingKey(itemId)]=rowDigest}return bindings}function derivePrReviewCriticInventory2(directory,state2,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state2,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state2,ctx){let composed=composePrReviewPhaseVerdicts(directory,state2,"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 deriveAuthoritativeCriticSettlements(directory,state2,ctx,criticInventory){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return criticInventory.map((findingId2)=>{let verdict=verdicts.get(findingId2);if(!verdict||verdict.status==="NEEDS_MORE_EVIDENCE")return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"};if(verdict.status==="UPHELD"||verdict.status==="DOWNGRADED"||verdict.status==="DISPROVED")return{findingId:findingId2,terminal:!0,status:verdict.status};return{findingId:findingId2,terminal:!1,status:"NEEDS_MORE_EVIDENCE"}})}async function readAuthoritativePrReviewCriticSettlements(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2),inventory=derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,"readAuthoritativePrReviewCriticSettlements");return deriveAuthoritativeCriticSettlements(directory,state2,ctx,inventory)}function deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx){return new Map([...authoritativeReviewerClaims2(directory,state2,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}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,state2,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state2,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state2,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state2,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state2,"critic",ctx),verdicts,origin),verdicts}async function readAuthoritativePrReviewCriticVerdicts(directory,sessionID){let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return authoritativeCriticVerdictsForGate(directory,state2,ctx,"write_pr_review_artifact critic settlement")}function derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state2,"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 derivePrReviewCriticInventory2(directory,state2,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_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record3,result,expected}=args2;if(expected.checkWorkflowLane&&record3.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record3.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record3.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record3.ownedWorkflowLanes??(record3.workflowLane?[record3.workflowLane]:[]));if(record3.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record3.mode??"(missing)");if(record3.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record3.workspace?.prHeadSha??"(missing)");if(record3.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record3.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record3.status!=="completed")return failedLaneValidation("record.status","completed",record3.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!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((record3)=>record3.laneId&&expectedByLaneId.has(record3.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record3 of relevantRecords){let laneRecords=recordsByLaneId.get(record3.laneId)??[];laneRecords.push(record3),recordsByLaneId.set(record3.laneId,laneRecords);let sessionId=record3.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 record3=laneRecords[0],subagentSessionId=record3.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record3.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(record3.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record3.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record3,result:record3.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record3.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record3.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record3,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let batchRead=findByBatchIdDetailed(directory,batchId,{parentSessionId:state2.sessionID});if(batchRead.status==="uncertain")throw Error(`BLOCKED: PR_REVIEW batch integrity cannot be analyzed for ${batchId}: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Restore the store and re-validate.`);let records=batchRead.value,analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state2.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_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state2,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope:state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state2,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful2.add(obligation)}return successful2}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 validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record3,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!==record3.batchId)return failedLaneValidation("artifact.batch_id",record3.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record3.laneId)return failedLaneValidation("artifact.lane_id",record3.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record3.subagentSessionId)return failedLaneValidation("artifact.session_id",record3.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record3.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record3.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record3.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record3.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record3.normalizedAgent)return failedLaneValidation("artifact.role",record3.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record3.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record3.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&&record3.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record3.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 loadArtifactPassingLaneIntegrity2(directory,state2,record3,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record3.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state2,record3,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record3.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state2,record3,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";return analyzeLegacyVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}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)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state2.mode==="PR_REVIEW"&&state2.prReviewBaseSha&&state2.prHeadSha?`complete PR diff ${state2.prReviewBaseSha}...${state2.prHeadSha}`:void 0,lastSubmitRejection=latestPrReviewSubmitRejectionMessage(state2,record3.subagentSessionId),validation=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:record3.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state2.workflowInstanceId,workflowRevision:record3.workflowGeneration,baseSha:state2.prReviewBaseSha,reviewScope},...lastSubmitRejection?{lastSubmitRejection}:{}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));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=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record3.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}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,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,cleanAttestationSalvaged=!1,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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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:acceptPartial,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);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");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)||Boolean(parsed.clean_attestation_salvaged)||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,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,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,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};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,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion2(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,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return recordIntegrity;let structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt",`missing structured receipt (legacy transcript adapter disabled)${input.lastSubmitRejection?`; last rejected submit_pr_review_result: ${input.lastSubmitRejection.slice(0,300)}`:""}`);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,input.result.transcriptIncomplete===!0)})),salvagedLanes=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");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,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state2=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state2.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state2.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state2.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state2.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state2.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims2(input.directory,state2,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzeLegacyVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state2.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!legacyFeedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state2.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{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}async function persistState2(directory,state2){let validated=PrWorkflowGateStateSchema.parse(state2);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state2,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}function boundSalvageDisclosure(sessionID,schemaErrors,coordinationNotice,revisionSalvageable=!0,armedShapeUnreadable=!1,publicationShapeUnreadable=!1){let disclosure=`DEGRADED: PR workflow gate state for session "${sessionID}" `+(coordinationNotice?`${coordinationNotice} and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). `:"failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). ")+`Schema errors: ${schemaErrors.join("; ")}.`+(revisionSalvageable?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":""),maxDisclosureChars=MAX_SALVAGED_SCHEMA_ERROR_CHARS*12;return disclosure.length<=maxDisclosureChars?disclosure:`${disclosure.slice(0,maxDisclosureChars-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")return{state:coordination.state,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationCorrupt=coordination.kind==="corrupt",coordinationGeneration=coordinationCorrupt?coordination.generation:void 0,coordinationReason=coordinationCorrupt?coordination.reason:void 0,filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp8.readFile(filePath,"utf-8")}catch(error93){if(error93.code==="ENOENT")return null;throw error93}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(parsed.success){if(parsed.data.sessionID!==normalizedSessionID||coordinationGeneration!==void 0&&parsed.data.revision!==coordinationGeneration)throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(!coordinationCorrupt)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let coordinationSchemaError=boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`);return{state:parsed.data,salvaged:!0,schemaErrors:[coordinationSchemaError],disclosure:boundSalvageDisclosure(normalizedSessionID,[coordinationSchemaError],"coordination authority was corrupt and the valid shadow projection was used"),revisionSalvageable:!0,armedShapeUnreadable:!1}}let invalidError=Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(typeof parsedJson!=="object"||parsedJson===null||Array.isArray(parsedJson))throw invalidError;let rawRecord=parsedJson,salvagedSessionID=exports_external.string().min(1).safeParse(rawRecord.sessionID),salvagedMode=exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).safeParse(rawRecord.mode);if(!salvagedSessionID.success||!salvagedMode.success||salvagedSessionID.data!==normalizedSessionID)throw invalidError;let salvagedRevision=exports_external.number().int().nonnegative().safeParse(rawRecord.revision),salvagedHead=exports_external.string().min(1).safeParse(rawRecord.prHeadSha),salvagedActivatedAt=exports_external.string().min(1).safeParse(rawRecord.activatedAt),salvagedUpdatedAt=exports_external.string().min(1).safeParse(rawRecord.updatedAt);if(coordinationGeneration!==void 0&&(!salvagedRevision.success||salvagedRevision.data!==coordinationGeneration))throw invalidError;let armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,shadowSchemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue3)=>boundSalvagedSchemaError(`${issue3.path.join(".")||"(root)"}: ${issue3.message}`)),schemaErrors=[...coordinationCorrupt?[boundSalvagedSchemaError(`coordination_state.payload: ${coordinationReason}`)]:[],...shadowSchemaErrors].slice(0,MAX_SALVAGED_SCHEMA_ERRORS),disclosure=boundSalvageDisclosure(normalizedSessionID,schemaErrors,coordinationCorrupt?`coordination authority was corrupt (${coordinationReason}) and the shadow projection was used`:void 0,salvagedRevision.success,armedShapeUnreadable,publicationShapeUnreadable);return{state:{schemaVersion:GATE_SCHEMA_VERSION,revision:salvagedRevision.success?salvagedRevision.data:0,sessionID:salvagedSessionID.data,mode:salvagedMode.data,activatedAt:salvagedActivatedAt.success?salvagedActivatedAt.data:isoNow(),updatedAt:salvagedUpdatedAt.success?salvagedUpdatedAt.data:isoNow(),...salvagedHead.success?{prHeadSha:salvagedHead.data}:{},...salvagedArmed.success?{prFeedbackReadyToPublish:salvagedArmed.data}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}var 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,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,MAX_PR_REVIEW_SUBMIT_REJECTIONS=24,GATE_SCHEMA_VERSION=1,MAX_WORKFLOW_BATCHES=128,MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS=128,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_PR_WORKFLOW_GATE_ENTRY_NAME_CHARS=240,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,MAX_DISCLOSED_LANE_IDS=10,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,CAS_ESCAPE_DISCLOSURE="state revision unsalvageable; cleared without compare-and-swap",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS=180000,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON="probe-skipped-no-budget",laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,DELEGATION_READ_UNCERTAIN_LOG_LIMIT=64,delegationReadUncertainLogged,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,PrReviewFindingPolicySynthesisFindingSchema,PrReviewCriticSettlementEvidenceSchema,PrReviewFindingPolicySynthesisSchema,_test_exports2,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,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,MAX_SALVAGED_SCHEMA_ERRORS=10,MAX_SALVAGED_SCHEMA_ERROR_CHARS=240;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_collection_receipt();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_finding_policy();init_legacy_transcript_adapter();init_persistence();init_reducer();init_scope_binding();init_state2();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();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};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,MAX_PR_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),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).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.optional()}).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(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).strict(),PrFeedbackInventoryAmendmentRecordSchema=exports_external.object({entry:exports_external.string().min(1),amendedAt:exports_external.string().min(1),batch:exports_external.number().int().positive()}).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).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).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(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").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(),prReviewResilience:PrReviewResilienceStateRecordSchema.optional(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).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(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).optional(),prReviewSubmitRejections:exports_external.array(exports_external.object({childSessionId:exports_external.string().min(1).max(200),laneId:exports_external.string().min(1).max(200).optional(),at:exports_external.number(),message:exports_external.string().min(1).max(300)}).strict()).max(MAX_PR_REVIEW_SUBMIT_REJECTIONS).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(),prFeedbackInventoryAmendments:exports_external.array(PrFeedbackInventoryAmendmentRecordSchema).max(MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS).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(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_WORKFLOW_STALE_LANE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES=new Set(["pending","running"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;delegationReadUncertainLogged=new Set;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;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"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);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(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).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(),PrReviewFindingPolicySynthesisFindingSchema=exports_external.object({id:exports_external.string().min(1).max(128),status:exports_external.string().min(1),severity:exports_external.string().min(1),action:exports_external.string().min(1)}).passthrough(),PrReviewCriticSettlementEvidenceSchema=exports_external.object({findingId:exports_external.string().min(1).max(128),terminal:exports_external.boolean(),status:exports_external.enum(["UPHELD","DOWNGRADED","DISPROVED","NEEDS_MORE_EVIDENCE"])}).passthrough(),PrReviewFindingPolicySynthesisSchema=exports_external.object({findings:exports_external.array(PrReviewFindingPolicySynthesisFindingSchema),criticSettlements:exports_external.array(PrReviewCriticSettlementEvidenceSchema).optional()});bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,workflowArtifactHasContractMarker,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),delegationReadUncertainLogged.clear(),_test_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforePrReviewReentryReservation=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return composePrReviewPhaseVerdicts(directory,state2,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCriticInventoryForCoverageGate(directory,state2,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state2=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state2);return derivePrReviewCandidateInventory2(directory,state2,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp8.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});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(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","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 /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens2=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens2[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,cancellationRequested=tokens2.includes(CANCEL_PUBLICATION_FLAG),reasonStartIndex=knownMode?1:0;if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
|
|
1313
1313
|
|
|
1314
1314
|
${USAGE2}`;if(cancellationRequested&&(knownMode!=="PR_FEEDBACK"||tokens2[1]!==CANCEL_PUBLICATION_FLAG))return`Error: ${CANCEL_PUBLICATION_FLAG} requires the exact form PR_FEEDBACK ${CANCEL_PUBLICATION_FLAG} <reason...>. It is not valid for PR_REVIEW or an unqualified force abort.
|
|
1315
1315
|
|
|
@@ -7628,11 +7628,11 @@ MICRO WORKED EXAMPLE:
|
|
|
7628
7628
|
${CANDIDATE_HEADERS.micro_lane}
|
|
7629
7629
|
[CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
|
|
7630
7630
|
Zero findings: ${CLEAN_TEMPLATES.micro_lane}
|
|
7631
|
-
${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt."),pr_review_contract_retry:exports_external.boolean().optional().describe("PR_REVIEW base-only contract retry marker. Use only for one admitted retry of exactly one dimension whose previous terminal record was a contract failure; it is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt and does not consume staged retry budget.")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals260={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep5};class PrReviewStructuredPromptUnsupportedError extends Error{constructor(message="structured PR-review prompt transport is unsupported"){super(message);this.name="PrReviewStructuredPromptUnsupportedError"}}function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;return{enabled:configured.enabled,canary_probe_ms:policy?.canaryProbeMs??configured.canary_probe_ms,status_probe_timeout_ms:policy?.statusProbeTimeoutMs??configured.status_probe_timeout_ms,correlated_failure_threshold:policy?.correlatedFailureThreshold??configured.correlated_failure_threshold,max_retry_attempts_after_initial:policy?.maxRetryAttemptsAfterInitial??configured.max_retry_attempts_after_initial,circuit_open_duration_ms:policy?.circuitOpenDurationMs??configured.circuit_open_duration_ms}}async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals260.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals260.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=_internals260.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId,duplicateRead=findByBatchIdDetailed(directory,batchId);if(duplicateRead.status==="uncertain")return asyncFailureResult({failure_class:"invalid_args",message:`batch uniqueness unverifiable: delegation store unreadable after ${duplicateRead.attempts} attempts (${duplicateRead.reason})`,errors:[`batch_id uniqueness could not be verified: ${batchId}; retry once the delegation store is readable`]});if(duplicateRead.value.length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,prReviewWorkflowInstanceId,prReviewWorkflowRevision,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(parsed.data.pr_review_contract_retry&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_contract_retry is valid only when mode is exactly "swarm-pr-review:base".'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals260.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals260.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest5)=>digest5?{ok:!0,digest:digest5}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals260.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let formatExplorerLanes=(input)=>applyExplorerFormatSuffix(input,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode}),contractPromptLanes=(input)=>applyPrWorkflowPromptContract(input,{mode:parsed.data.mode,batchId:parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro"?batchId:void 0,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(parsed.data.pr_review_wave_stage==="fanout"||(parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro")&&parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??0)>0)){let formatted=formatExplorerLanes(lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});let contracted=contractPromptLanes(formatted.lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=contracted.lanes}else{let contracted=contractPromptLanes(lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=formatExplorerLanes(contracted.lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});lanes=formatted.lanes}if(context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){let configuredResilience=_internals260.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),contractRetry=parsed.data.pr_review_contract_retry===!0,waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(contractRetry&&(waveStage!==void 0||waveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&!contractRetry&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0,effectiveMaxConcurrent=parsed.data.max_concurrent??parsed.data.lanes.length;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||effectiveMaxConcurrent!==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||effectiveMaxConcurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||effectiveMaxConcurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(effectiveMaxConcurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals260.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope,prReviewWorkflowInstanceId,prReviewWorkflowRevision}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&(parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_contract_retry===!0))try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId,parsed.data.pr_review_contract_retry===!0)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected2.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected2.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals260.now()+timeoutMs,hostTimeouts=new Set,collectionResourceFailures=new Map,receiptAppendFailureLogs=new Set,settleFailureLogs=new Map,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,initialRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(initialRead.status==="uncertain")return collectFailureResult({failure_class:"store_unreadable",batch_id:parsed.data.batch_id,message:`Delegation store unreadable after ${initialRead.attempts} attempts; batch ${parsed.data.batch_id} is UNKNOWN, not absent (${initialRead.reason})`});let records=initialRead.value;if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});await recoverTerminalLaneReceipts(directory,records);let revisionSnapshots=new Map,session=_internals260.getSessionOps();if(!session||typeof session.messages!=="function"){let reviewReceiptFallbacks2=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result2=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks2}),observed=reducePrReviewEvent({sessionID:context.sessionID??"",revision:0},{type:"collection_observed",diagnostic:"host_unavailable",pendingLaneIds:records.filter((record3)=>!isTerminalDelegationStatus2(record3.status)).map((record3)=>record3.laneId??record3.correlationId)}),diagnosticCode=observed.status==="applied"?observed.effects.find((effect)=>effect.kind==="emit_diagnostic")?.code??"collection_host_unavailable":"collection_host_unavailable";return result2.failure_class="no_client",result2.message="OpenCode session messages client is not available; lane state is reported as stored and no lane was cancelled or terminalized. Poll again once the host client is available, cancel explicitly, or rely on the presumed-stale backstop.",result2.errors=[`OpenCode session messages client is not available (${diagnosticCode})`],await attachPendingLaneLiveness(result2,directory,records,deadline),result2}let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts);let pollRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(pollRead.status==="uncertain"){if(addLaneDiagnostic(collectionResourceFailures,`batch:${parsed.data.batch_id}`,`collect re-read uncertain: delegation store unreadable after ${pollRead.attempts} attempts (${pollRead.reason}); settlement UNKNOWN, continuing to poll`),parsed.data.wait!==!0){keepPolling=!1;continue}}else if(records=pollRead.value,allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals260.now()>=deadline){keepPolling=!1;continue}await _internals260.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals260.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(await attachPendingLaneLiveness(result,directory,records,deadline),hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.";let diagnostics=assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures);if(diagnostics.length>0)result.errors=diagnostics;return result}async function attachPendingLaneLiveness(result,directory,records,deadline){if(result.pending<=0)return;let pendingLiveness=await collectPrWorkflowPendingLaneLiveness(directory,records,{probeBudgetMs:Math.max(0,deadline-_internals260.now())});if(pendingLiveness.length>0)result.pending_liveness=pendingLiveness}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key:key2}=current;if((key2==="isRetryable"||key2==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key2===void 0||CREATE_FAILURE_STATUS_KEYS.has(key2)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key2!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key2))continue;if(key2!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key2)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:key2})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,legacyTranscriptCompatibility=args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"?prReviewLegacyTranscriptCompatibilityEnabled(_internals260.loadPluginConfig(args2.directory).pr_review_legacy_transcript_compatibility):void 0,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:args2.prReviewWorkflowInstanceId?encodePrReviewWorkflowBinding(args2.prReviewWorkflowInstanceId):null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,prReviewLegacyTranscriptCompatibility:legacyTranscriptCompatibility,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},...args2.prReviewWorkflowRevision!==void 0?{workflowGeneration:args2.prReviewWorkflowRevision}:{},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return emitDelegationBegin(pendingOutcome.record),scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs,mode:args2.mode,structuredAdapter:args2.context.prReviewStructuredPromptAdapter}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running"),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],laneLabel=record3.laneId??record3.correlationId,remainingLaneCount=activeRecords.length-index,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,typeof session.status==="function",needsRevisionDigest);if(cancelPending){if(typeof session.abort==="function"){let timeoutCount=hostTimeouts.size;try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts,laneBudgets.laneBudgetMs)}catch{if(hostTimeouts.size>timeoutCount)continue}}await settleDelegationTerminal(directory,record3,{status:"cancelled",result:{error:"lane cancelled via collect_lane_results cancel_pending",chars:0,truncated:!1,digest:digestText2(""),workflowLaneFailureClass:"liveness"}},{},_internals260.now());continue}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")continue;let messages;try{messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${laneLabel}"`,hostTimeouts,laneBudgets.messagesBudgetMs)}catch(error93){let messageTimeoutPrefix=`session.messages for lane "${laneLabel}" exceeded the remaining collect_lane_results budget`;if(![...hostTimeouts].some((entry)=>entry.startsWith(messageTimeoutPrefix)))addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages transport error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);continue}if(!messages.data){if(messages.error)addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages returned an error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(messages.error)}`);continue}clearLaneDiagnostics(collectionResourceFailures,laneLabel);let transcript=extractAssistantTranscript(messages.data),relyingOnCompletedAtOnly=readiness!=="idle"&&Number.isFinite(transcript.completedAt),hostSaysRetryable=transcript.terminalError?.kind!=="aborted"&&transcript.terminalError?.hostRetryable===!0;if(transcript.terminalError&&!transcript.text&&!transcript.windowTruncated&&(Number.isFinite(transcript.completedAt)||readiness==="idle")&&!(relyingOnCompletedAtOnly&&hostSaysRetryable)){let settledStatus=transcript.terminalError.kind==="aborted"?"cancelled":"error",reason=laneTerminalErrorReason(transcript.terminalError),settled=await settleDelegationTerminal(directory,record3,{status:settledStatus,result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),terminalErrorClass:terminalErrorClassFromLaneTerminalError(transcript.terminalError)}},{},_internals260.now());if(settled.kind==="claimed")clearLaneDiagnostics(settleFailureLogs,laneLabel),cleanupAsyncLaunchSession(session,record3.subagentSessionId);else if(isBenignSettleOutcome(settled.kind))clearLaneDiagnostics(settleFailureLogs,laneLabel);else if(settled.kind==="uncertain")addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle deferred for lane "${laneLabel}"; delegation store unreadable (${settled.reason??"unclassified"}); lane left open for retry`);else addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle write did not land for lane "${laneLabel}"; lane left open`);continue}if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}))}await Promise.all(pendingSettlements)}function revisionSnapshotKey(directory,prHeadSha){return`${canonicalRootKeyFresh(directory)}\x00${prHeadSha??""}`}var MAX_DIAGNOSTICS_PER_LANE=3,MAX_HOST_TIMEOUT_DIAGNOSTICS=MAX_LANES*4,MAX_LANE_DIAGNOSTICS_PER_CHANNEL=MAX_LANES*MAX_DIAGNOSTICS_PER_LANE;function assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures){return[...flattenLaneDiagnostics(settleFailureLogs),...flattenLaneDiagnostics(collectionResourceFailures),...[...hostTimeouts].slice(0,MAX_HOST_TIMEOUT_DIAGNOSTICS)]}function addLaneDiagnostic(diagnostics,laneLabel,message){let entries2=diagnostics.get(laneLabel);if(entries2===void 0)entries2=new Set,diagnostics.set(laneLabel,entries2);if(entries2.has(message))return;if(entries2.size>=MAX_DIAGNOSTICS_PER_LANE)return;entries2.add(message)}function clearLaneDiagnostics(diagnostics,laneLabel){diagnostics.delete(laneLabel)}function flattenLaneDiagnostics(diagnostics){let flat=[];for(let entries2 of diagnostics.values())for(let entry of entries2){if(flat.length>=MAX_LANE_DIAGNOSTICS_PER_CHANNEL)return flat;flat.push(entry)}return flat}var MAX_DIAGNOSTIC_CAUSE_CHARS=160;function safeDiagnosticCause(error93){let redacted=sanitizeFailureEvidenceDisplay(formatError3(error93));if(redacted.length===0)return"(no detail)";return redacted.length>MAX_DIAGNOSTIC_CAUSE_CHARS?`${redacted.slice(0,MAX_DIAGNOSTIC_CAUSE_CHARS)}…`:redacted}function resolveCollectExpectedWorkflowIdentity(record3,parentState){if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"&&record3.mode!=="swarm-pr-review:council")return;let workflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),workflowRevision=record3.workflowGeneration;if(!workflowInstanceId||workflowRevision===void 0)return;if(!parentState||parentState.mode!=="PR_REVIEW")return;if(parentState.workflowInstanceId!==workflowInstanceId)return;let baseSha=parentState.prReviewBaseSha;if(!baseSha)return;return{workflowInstanceId,workflowRevision,baseSha}}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}=args2,laneLabel=record3.laneId??record3.correlationId,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{let key2=revisionSnapshotKey(directory,prHeadSha),snapshot2=revisionSnapshots.get(key2);if(snapshot2===void 0){snapshot2=_internals260.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha);let pending=snapshot2;pending.catch(()=>{if(revisionSnapshots.get(key2)===pending)revisionSnapshots.delete(key2)}),revisionSnapshots.set(key2,pending)}let shared=snapshot2;collectedRevisionDigest=await withCollectionDeadline(()=>shared,deadline,`revision digest for lane "${laneLabel}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch(error93){addLaneDiagnostic(settleFailureLogs,laneLabel,`revision snapshot unavailable for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);return}clearLaneDiagnostics(settleFailureLogs,laneLabel);let output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount,...record3.result?.prReviewResultReceipt?{prReviewResultReceipt:record3.result.prReviewResultReceipt}:{}},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,collectExpectedIdentity;if(record3.parentSessionId?.trim())try{let parentState=await readPrWorkflowGateStateFromDisk(directory,record3.parentSessionId.trim());collectExpectedIdentity=resolveCollectExpectedWorkflowIdentity(record3,parentState)}catch{collectExpectedIdentity=void 0}let validation2=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0,...collectExpectedIdentity??{}}});if(validation2.ok&&validation2.salvaged?.length){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error",prospectiveResult.workflowLaneFailureClass="contract";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals260.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{},_internals260.now());return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode3=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode3}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{transcript:transcript.text,startedAt:record3.createdAt,model:laneConfiguredModel(record3)},_internals260.now())}function laneConfiguredModel(record3){let prefixed=record3.swarmPrefixedAgent,baseRole=stripKnownSwarmPrefix(prefixed),swarmID=baseRole!==prefixed?prefixed.slice(0,prefixed.length-baseRole.length-1):void 0;return getSwarmAgents(swarmID)?.[baseRole]?.model}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key2=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key2))return!1;return loggedFailures.add(key2),!0}class LanePromptLaunchRejectionError extends Error{constructor(message){super(message);this.name="LanePromptLaunchRejectionError"}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){if(args2.structuredAdapter&&(args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"))try{await withTimeout2(args2.structuredAdapter.promptJsonSchema({sessionId:args2.sessionId,agent:args2.lane.agent,schema:exports_external.toJSONSchema(PrReviewLaneResultEnvelopeSchema),parts:[{type:"text",text:args2.lane.prompt}]}),args2.timeoutMs,`Lane "${args2.lane.id}" structured PR-review launch timed out after ${args2.timeoutMs}ms`);return}catch(error93){if(!(error93 instanceof PrReviewStructuredPromptUnsupportedError)){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}}let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),lanePrimaryModel=swarmAgents?.[baseRole]?.model,laneFallbackModels=swarmAgents?.[baseRole]?.fallback_models??[],registry4=_internals260.getGeneratedAgentNames();if(registry4.length>0&&!registry4.some((name)=>name.toLowerCase()===args2.lane.agent.toLowerCase())&&!swarmAgents?.[baseRole]&&!lanePrimaryModel&&laneFallbackModels.length===0){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`Lane "${args2.lane.id}" agent "${args2.lane.agent}" resolves no registered swarm agent and no model; refusing to launch a lane the host cannot run`);return}let promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(args2.mode),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw new LanePromptLaunchRejectionError(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals260.now()+args2.timeoutMs,now:_internals260.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){let recordRead=findByCorrelationIdDetailed(directory,sessionId);if(recordRead.status==="uncertain"){warnDelegationReadUncertainOnce2(`launch-error settle skipped for lane session ${sessionId}`,recordRead),cleanupAsyncLaunchSession(session,sessionId);return}let record3=recordRead.value,launchErrorResult={error:message,chars:message.length,truncated:!1,digest:digestText2(message),workflowLaneFailureClass:"resource"};if(record3)await settleDelegationTerminal(directory,record3,{status:"error",result:launchErrorResult},{},_internals260.now());else await appendDelegationTransition(directory,sessionId,{status:"error",result:launchErrorResult,terminalResult:buildTypedDelegationTerminal({correlationId:sessionId,jobId:null},"error",launchErrorResult,_internals260.now())});cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";try{let status2=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status2.error||!status2.data)return"unknown";let current=status2.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}var DELEGATION_READ_UNCERTAIN_LOG_LIMIT2=64,delegationReadUncertainLogged2=new Set;function warnDelegationReadUncertainOnce2(label,uncertain){let key2=`${label}\x00${uncertain.reason}`;if(delegationReadUncertainLogged2.has(key2))return;if(delegationReadUncertainLogged2.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT2){let oldest=delegationReadUncertainLogged2.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged2.delete(oldest)}delegationReadUncertainLogged2.add(key2),warn(`${label}: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); skipping this pass`)}var SWEEP_LIVENESS_SETTLE_BUDGET_MS=250;async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals260.now(),settleReserveMs=Math.min(SWEEP_LIVENESS_SETTLE_BUDGET_MS,Math.max(0,deadline-now2));for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;let statusBudgetMs=reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs;if(!(typeof session.status!=="function"||settleReserveMs>0&&deadline-_internals260.now()>0))continue;let readiness=await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,Math.max(statusBudgetMs,settleReserveMs));if(readiness==="busy")continue;if(readiness==="unknown"){let currentUnknown=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentUnknown)continue;if(currentUnknown.result)continue;let reason=`lane ${currentUnknown.laneId??currentUnknown.correlationId} presumed dead: host session unobservable`;await settleDelegationTerminal(directory,currentUnknown,{status:"error",result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),workflowLaneFailureClass:"liveness"}},{},_internals260.now());continue}let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;let idleStaleReason=`lane ${currentAfterReadiness.laneId??currentAfterReadiness.correlationId} presumed stale: idle host session past the stale horizon`,idleLivenessResult=currentAfterReadiness.result?{...currentAfterReadiness.result,workflowLaneFailureClass:"liveness"}:{error:idleStaleReason,chars:idleStaleReason.length,truncated:!1,digest:digestText2(idleStaleReason),workflowLaneFailureClass:"liveness"},idleTerminal=buildTypedDelegationTerminal(currentAfterReadiness,"stale",idleLivenessResult,_internals260.now());await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",result:idleLivenessResult,expectedCurrentStatuses:["pending","running","ingestion_error"],terminalResult:idleTerminal})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&¤t.status!=="running"&¤t.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),status2=error93.statusCode===void 0?"":` status=${error93.statusCode}`,retryable=error93.hostRetryable===void 0?"":` host_retryable=${error93.hostRetryable}`;return`${error93.category}: ${message} [kind=${error93.kind} name=${error93.name}${status2}${retryable}]`}function terminalErrorClassFromLaneTerminalError(error93){let category=error93.category.trim().length>0?error93.category.trim().slice(0,128):"unknown";return{kind:error93.kind,category,...error93.statusCode===void 0?{}:{statusCode:error93.statusCode},...error93.hostRetryable===void 0?{}:{hostRetryable:error93.hostRetryable}}}function readErrorDataRecord(error93){if(typeof error93!=="object"||error93===null)return{};let data=error93.data;return typeof data==="object"&&data!==null?data:{}}function classifyLaneTerminalError(error93){let name=typeof error93?.name==="string"?error93.name.slice(0,64):"UnknownError",data=readErrorDataRecord(error93),topLevelMessage=error93?.message,rawMessage=typeof data.message==="string"&&data.message.trim().length>0?data.message:typeof topLevelMessage==="string"&&topLevelMessage.trim().length>0?topLevelMessage:typeof error93==="string"&&error93.trim().length>0?error93:name,statusCode=typeof data.statusCode==="number"&&Number.isFinite(data.statusCode)?data.statusCode:void 0,hostRetryable=typeof data.isRetryable==="boolean"?data.isRetryable:void 0,kind=name==="MessageAbortedError"?"aborted":name==="MessageOutputLengthError"?"output_length":name==="APIError"||name==="ProviderAuthError"?"provider":"unknown",classified=classifyProviderFailure(statusCode===void 0?rawMessage:{message:rawMessage,status:statusCode}),category=kind==="aborted"?"provider.cancelled":classified.category;return{kind,name,message:classified.evidence.display,statusCode:statusCode??classified.evidence.statusCode,hostRetryable,category}}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
|
|
7631
|
+
${EXPLORER_CANDIDATE_COMMON_END}`,READ_ONLY_LANE_ROLES=new Set(["explorer","reviewer","test_engineer","critic","critic_oversight","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","critic_finding_validator","sme","researcher","council_generalist","council_skeptic","council_domain_expert"]),READ_ONLY_TOOL_DENYLIST=[...new Set([...WRITE_TOOL_NAMES,"extract_code_blocks","multiedit","multi_edit","todo_write","save_plan","update_task_status","phase_complete","declare_scope","declare_council_criteria","submit_council_verdicts","submit_phase_council_verdicts","set_qa_gates","write_retro","write_drift_evidence","write_hallucination_evidence","write_mutation_evidence","knowledge_add","knowledge_remove","consensus_mine","summarize_work","doc_scan","lint"])],LaneSchema=exports_external.object({id:exports_external.string().min(1).max(80).regex(/^[A-Za-z0-9][A-Za-z0-9_.-]*$/).describe("Stable lane identifier, unique within this dispatch batch"),agent:exports_external.string().min(1).max(120).describe("Read-only swarm agent name, including any generated swarm prefix"),prompt:exports_external.string().min(1).max(MAX_PROMPT_CHARS).describe("Full lane prompt to send to the requested agent"),workflow_lane:exports_external.string().min(1).max(120).optional().describe("Required mechanical policy identifier in PR workflows; distinct from the retry-safe lane id"),owned_workflow_lanes:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).max(11).optional().describe("Complete dimension/family set a consolidated PR-review base or micro lane covers under the controller-computed depth tier; must include workflow_lane. Omit for singleton lanes."),feedback_item_ids:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("PR-feedback ledger item IDs owned exclusively by this lane"),review_item_ids:exports_external.array(exports_external.string().trim().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional().describe("Candidate/finding IDs owned by a PR-review reviewer or critic lane; every ID requires a parseable verdict row")}),DispatchLanesArgsSchema=exports_external.object({lanes:exports_external.array(LaneSchema).min(1).max(MAX_LANES).describe("Read-only lane specs to dispatch concurrently"),common_prompt:exports_external.string().min(1).regex(/\S/,"common_prompt must contain non-whitespace content").max(MAX_PROMPT_CHARS-COMMON_PROMPT_SEPARATOR.length-1).optional().describe("Optional shared context prepended to every lane prompt. Send large shared context (PR diff, obligation ledger, scope) ONCE here instead of inlining the same blob into each lane prompt; this keeps the tool-call payload small and avoids malformed/truncated tool-call JSON. Combined common_prompt + per-lane prompt must not exceed the per-lane character limit."),max_concurrent:exports_external.number().int().min(1).max(MAX_LANES).optional().describe("Maximum lanes in flight at once; defaults to lane count"),timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Per-lane timeout in milliseconds. For blocking dispatch this covers session create and prompt execution; for async dispatch this covers launch only, never lane runtime."),orientation:exports_external.boolean().optional().describe("Prepend a bounded, deterministic repo-graph orientation block (mission-relevant files, repo hubs, freshness line) to common_prompt when the repo graph is fresh and relevant. No schema default: availability depends on graph state, resolved at execute time (omitted ⇒ attempted, skipped when no fresh graph exists). Explicitly false disables the block entirely.")}),DispatchLanesAsyncArgsSchema=DispatchLanesArgsSchema.extend({launch_timeout_ms:exports_external.number().int().min(10).max(MAX_TIMEOUT_MS4).optional().describe("Async launch acceptance timeout in milliseconds. This only bounds session creation and promptAsync acceptance; it is never a lane runtime timeout. Deprecated alias: timeout_ms."),batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS).regex(/^[A-Za-z0-9][A-Za-z0-9_.:-]*$/).optional().describe("Stable async batch id for later collection; generated when omitted"),mode:exports_external.string().min(1).max(80).optional().describe('Advisory workflow mode, such as deep-dive. PR-review stages are COLON-SUFFIXED and the suffix is required. Accepted values: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic, swarm-pr-feedback:verification. A bare "swarm-pr-review" does NOT enter the PR-review path — it skips the merge-base bind and later fails with "exact merge-base scope was not verified".'),pr_head_sha:exports_external.string().min(1).max(80).optional().describe("Full 40-char SHA of the PR head commit under review. Required when mode starts with swarm-pr-review: or swarm-pr-feedback:."),base_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i).optional().describe("Exact merge base of base_ref and pr_head_sha — NOT the base branch tip. The controller recomputes `git merge-base -- <base_ref> <pr_head_sha>` and rejects any mismatch. Required when mode starts with swarm-pr-review:."),base_ref:exports_external.string().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/).optional().describe("Base branch ref used to recompute the merge base. Use the REMOTE-TRACKING form (origin/main), and compute base_sha against that same ref. A local branch ref (main, refs/heads/main) is only as fresh as the last fetch — the PR-review preflight fetches refs/pull/<N>/head and not the base branch, so a local ref commonly resolves to a different merge base and the dispatch is rejected. Required when mode starts with swarm-pr-review:."),scope:exports_external.string().min(1).max(500).optional(),trigger_evaluation:exports_external.array(PrReviewInlineTriggerRowSchema).min(1).optional().describe("Complete repository-agnostic trigger ledger required for the first swarm-pr-review:micro dispatch. The first successful micro dispatch freezes it in same-session workflow state; any subsequent micro batch may omit this property and reuse that exact frozen ledger. If supplied later, it must remain exactly identical. MATCHED families are dispatched and inapplicable families are NOT_TRIGGERED."),feedback_inventory:exports_external.array(exports_external.string().trim().min(1).max(120)).min(1).optional().describe("Complete immutable feedback item inventory required for swarm-pr-feedback:verification"),pr_review_wave_stage:exports_external.enum(["canary","fanout"]).optional().describe('PR_REVIEW base-only staged dispatch marker. Required with pr_review_wave_attempt at depth tier M or L while pr_review_resilience is enabled. Use "canary" for the singleton probe lane and "fanout" for the follow-up batch that partitions the remaining unresolved base obligations.'),pr_review_wave_attempt:exports_external.number().int().min(0).max(2).optional().describe("PR_REVIEW base-only staged attempt number, required together with pr_review_wave_stage at depth tier M or L while resilience is enabled: attempt 0 is the initial wave, followed by at most two retry attempts (1 and 2) over the exact unresolved-obligation target left by the previous attempt."),pr_review_contract_retry:exports_external.boolean().optional().describe("PR_REVIEW base-only contract retry marker. Use only for one admitted retry of exactly one dimension whose previous terminal record was a contract failure; it is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt and does not consume staged retry budget.")}),CollectLaneResultsArgsSchema=exports_external.object({batch_id:exports_external.string().min(1).max(MAX_BATCH_ID_CHARS),wait:exports_external.boolean().optional().describe("Poll until all lanes settle or timeout"),timeout_ms:exports_external.number().int().min(0).max(MAX_COLLECT_TIMEOUT_MS).optional().describe("Total wait budget when wait=true"),include_pending:exports_external.boolean().optional().describe("Include pending/running lanes in lane_results. Defaults to true for non-blocking polls and false for wait=true joins."),cancel_pending:exports_external.boolean().optional().describe("Abort and mark pending/running lanes cancelled")});function validatePrReviewMicroDispatch(args2,depthTier){let evaluation=args2.trigger_evaluation;if(!evaluation)throw Error("BLOCKED: initial PR_REVIEW micro dispatch requires the complete trigger_evaluation ledger; after the first successful same-session micro dispatch freezes it, a later micro batch may omit the property and reuse that exact ledger");let validated;try{validated=validatePrReviewInlineTriggerLedger(evaluation)}catch(error93){throw Error(`BLOCKED: ${error93 instanceof Error?error93.message:String(error93)}`)}let required3=new Set(validated.matchedIds),laneOwnership=args2.lanes.map((lane)=>({label:lane.workflow_lane??"",owned:lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]}));if(depthTier==="L"&&laneOwnership.some((lane)=>lane.owned.length!==1))throw Error("BLOCKED: PR_REVIEW micro dispatch at depth tier L requires one dedicated lane per risk family; consolidated owned_workflow_lanes are allowed only at tiers S and M");let flattened=laneOwnership.flatMap((lane)=>lane.owned),duplicates=flattened.filter((value,index)=>flattened.indexOf(value)!==index),unmatched=flattened.filter((triggerId)=>!required3.has(triggerId)),invalidLabels=laneOwnership.filter((lane)=>lane.label.length===0||!lane.owned.includes(lane.label)).map((lane)=>lane.label||"(missing workflow_lane)");if(invalidLabels.length>0||duplicates.length>0||unmatched.length>0)throw Error(`BLOCKED: PR_REVIEW micro lanes must have unique workflow_lane IDs from the mandatory repository-agnostic lane set, with workflow_lane contained in its own owned set; invalid: ${[...new Set([...invalidLabels,...duplicates,...unmatched])].join(", ")}`);let coversAllFamilies=required3.size>0&&[...required3].every((id)=>flattened.includes(id)),microFloor=Math.min(PR_REVIEW_MICRO_LANE_FLOORS[depthTier],required3.size);if(coversAllFamilies&&laneOwnership.length<microFloor)throw Error(`BLOCKED: PR_REVIEW micro dispatch at depth tier ${depthTier} covering all ${required3.size} matched risk families requires at least ${microFloor} lanes; received ${laneOwnership.length}. Partial retry batches covering a subset of matched families are exempt; NOT_TRIGGERED families must not be dispatched.`)}var _internals260={getSessionOps:()=>swarmState.opencodeClient?.session??null,getGeneratedAgentNames:()=>swarmState.generatedAgentNames,createParallelDispatcher,loadPluginConfig,resolvePrWorkflowRevisionDigestAsync,resolveExactMergeBaseAsync,validatePrWorkflowTransportRecovery,now:()=>Date.now(),sleep:sleep5};class PrReviewStructuredPromptUnsupportedError extends Error{constructor(message="structured PR-review prompt transport is unsupported"){super(message);this.name="PrReviewStructuredPromptUnsupportedError"}}function effectivePrReviewResilienceConfig(configured,gateState){let policy=gateState?.prReviewResilience?.policy;return{enabled:configured.enabled,canary_probe_ms:policy?.canaryProbeMs??configured.canary_probe_ms,status_probe_timeout_ms:policy?.statusProbeTimeoutMs??configured.status_probe_timeout_ms,correlated_failure_threshold:policy?.correlatedFailureThreshold??configured.correlated_failure_threshold,max_retry_attempts_after_initial:policy?.maxRetryAttemptsAfterInitial??configured.max_retry_attempts_after_initial,circuit_open_duration_ms:policy?.circuitOpenDurationMs??configured.circuit_open_duration_ms}}async function executeDispatchLanes(args2,directory,context={}){let parsed=DispatchLanesArgsSchema.safeParse(args2);if(!parsed.success)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:boundZodIssues(parsed.error.issues)});let duplicateLaneIds=findDuplicateLaneIds(parsed.data.lanes);if(duplicateLaneIds.length>0)return failureResult2({failure_class:"invalid_args",message:"Lane IDs must be unique within one dispatch_lanes batch",errors:duplicateLaneIds.map((id)=>`Duplicate lane id: ${id}`)});if(context.sessionID?.trim())try{await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes")}catch(error93){return failureResult2({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let session=_internals260.getSessionOps();if(!session)return failureResult2({failure_class:"no_client",message:"OpenCode session client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid dispatch_lanes arguments",errors:common.errors});let requiresMandatoryExplorerFormat=common.lanes.some((lane)=>lane.workflow_lane!==void 0||(lane.owned_workflow_lanes?.length??0)>0),formatted=applyExplorerFormatSuffix(common.lanes,{failClosed:requiresMandatoryExplorerFormat});if(!formatted.ok)return failureResult2({failure_class:"invalid_args",message:"Invalid explorer output-format contract",errors:formatted.errors});let lanes=formatted.lanes,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),timeoutMs=parsed.data.timeout_ms??DEFAULT_TIMEOUT_MS5,dispatcher=_internals260.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=_internals260.getSessionOps();if(!session||typeof session.promptAsync!=="function")return asyncFailureResult({failure_class:"no_client",message:"OpenCode session promptAsync client is not available"});let orientedCommonPrompt=await augmentCommonPromptWithOrientation(directory,parsed.data.lanes,parsed.data.common_prompt,parsed.data.orientation,context.sessionID),common=applyCommonPrompt(parsed.data.lanes,orientedCommonPrompt);if(!common.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid dispatch_lanes_async arguments",errors:common.errors});let lanes=common.lanes,batchId=requestedBatchId,duplicateRead=findByBatchIdDetailed(directory,batchId);if(duplicateRead.status==="uncertain")return asyncFailureResult({failure_class:"invalid_args",message:`batch uniqueness unverifiable: delegation store unreadable after ${duplicateRead.attempts} attempts (${duplicateRead.reason})`,errors:[`batch_id uniqueness could not be verified: ${batchId}; retry once the delegation store is readable`]});if(duplicateRead.value.length>0)return asyncFailureResult({failure_class:"invalid_args",message:`Async lane batch already exists: ${batchId}`,errors:[`batch_id must be unique: ${batchId}`]});let verifiedPrHead,workflowRevisionDigest,verifiedReviewBaseSha,prReviewWorkflowInstanceId,prReviewWorkflowRevision,bareWorkflowMode=["swarm-pr-review","swarm-pr-feedback"].find((prefix)=>parsed.data.mode?.trim()===prefix);if(bareWorkflowMode)return asyncFailureResult({failure_class:"invalid_args",message:bareWorkflowMode==="swarm-pr-review"?'BLOCKED: mode "swarm-pr-review" is missing its required stage suffix. Use one of: swarm-pr-review:base, swarm-pr-review:micro, swarm-pr-review:council, swarm-pr-review:reviewer, swarm-pr-review:critic.':'BLOCKED: mode "swarm-pr-feedback" is missing its required stage suffix. Use swarm-pr-feedback:verification.'});if((parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_wave_attempt!==void 0)&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_wave_stage and pr_review_wave_attempt are valid only when mode is exactly "swarm-pr-review:base".'});if(parsed.data.pr_review_contract_retry&&parsed.data.mode!=="swarm-pr-review:base")return asyncFailureResult({failure_class:"invalid_args",message:'BLOCKED: pr_review_contract_retry is valid only when mode is exactly "swarm-pr-review:base".'});if(context.sessionID?.trim()&&parsed.data.pr_head_sha&&(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")))try{verifiedPrHead=await assertCurrentCheckoutHead(directory,parsed.data.pr_head_sha,parsed.data.mode?.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":"PR_REVIEW");let resolvedDigest=_internals260.resolvePrWorkflowRevisionDigestAsync!==resolvePrWorkflowRevisionDigestAsync?await _internals260.resolvePrWorkflowRevisionDigestAsync(directory,parsed.data.pr_head_sha).then((digest5)=>digest5?{ok:!0,digest:digest5}:{ok:!1,reason:"seam-unavailable"}):await resolvePrWorkflowRevisionDigestDetailedAsync(directory,parsed.data.pr_head_sha);if(!resolvedDigest.ok)throw Error(`BLOCKED: PR workflow could not compute a bounded current-revision digest for pr_head_sha "${parsed.data.pr_head_sha}"; `+describePrWorkflowRevisionDigestFailure(resolvedDigest));if(workflowRevisionDigest=resolvedDigest.digest,parsed.data.mode?.startsWith("swarm-pr-review:")){if(!parsed.data.base_sha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW dispatch requires exact base_sha and base_ref");let resolvedBase=await _internals260.resolveExactMergeBaseAsync(directory,parsed.data.base_ref,parsed.data.pr_head_sha);if(!resolvedBase)throw Error(`BLOCKED: PR_REVIEW could not resolve a merge base for base_ref="${parsed.data.base_ref}" and pr_head_sha=${parsed.data.pr_head_sha} in "${directory}". The ref may not exist locally — the PR-review preflight fetches only refs/pull/<N>/head, not the base branch. Fetch it and pass the remote-tracking form using two separate standalone commands. First run: git -C "${directory}" fetch origin <base-branch>. Then run: git -C "${directory}" merge-base -- origin/<base-branch> ${parsed.data.pr_head_sha}`);if(resolvedBase.toLowerCase()!==parsed.data.base_sha.toLowerCase())throw Error(`BLOCKED: PR_REVIEW merge-base mismatch. git merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha} in "${directory}" resolved to ${resolvedBase}, but base_sha=${parsed.data.base_sha} was passed. If you computed base_sha against a remote-tracking ref, pass that SAME ref as base_ref — a local branch of the same name (main, refs/heads/main) may be stale and yields a different merge base. Verify with: git -C "${directory}" merge-base -- "${parsed.data.base_ref}" ${parsed.data.pr_head_sha}`);verifiedReviewBaseSha=resolvedBase}}catch(error93){return asyncFailureResult({failure_class:"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow checkout head verification failed"})}if(parsed.data.mode?.startsWith("swarm-pr-review:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: active PR_REVIEW dispatch requires pr_head_sha"});if(parsed.data.mode?.startsWith("swarm-pr-feedback:")&&!parsed.data.pr_head_sha)return asyncFailureResult({failure_class:"invalid_args",message:"BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha"});let formatExplorerLanes=(input)=>applyExplorerFormatSuffix(input,{failClosed:Boolean(parsed.data.mode?.startsWith("swarm-pr-review:")||parsed.data.mode?.startsWith("swarm-pr-feedback:")),mode:parsed.data.mode}),contractPromptLanes=(input)=>applyPrWorkflowPromptContract(input,{mode:parsed.data.mode,batchId:parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro"?batchId:void 0,prHeadSha:verifiedPrHead,revisionDigest:workflowRevisionDigest,scope:verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:"the complete immutable feedback inventory on the exact checked-out revision",callerFocus:parsed.data.scope});if(parsed.data.pr_review_wave_stage==="fanout"||(parsed.data.mode==="swarm-pr-review:base"||parsed.data.mode==="swarm-pr-review:micro")&&parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??0)>0)){let formatted=formatExplorerLanes(lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});let contracted=contractPromptLanes(formatted.lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});lanes=contracted.lanes}else{let contracted=contractPromptLanes(lanes);if(!contracted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow prompt contract",errors:contracted.errors});let formatted=formatExplorerLanes(contracted.lanes);if(!formatted.ok)return asyncFailureResult({failure_class:"invalid_args",message:"Invalid mandatory PR workflow explorer output contract",errors:formatted.errors});lanes=formatted.lanes}if(context.sessionID?.trim())try{let gateState=await enforcePrWorkflowDispatchLanesAsync(directory,context.sessionID,"dispatch_lanes_async");if(!gateState&&parsed.data.mode?.startsWith("swarm-pr-review:"))gateState=await activatePrWorkflow(directory,context.sessionID,"PR_REVIEW",{requireCheckoutPreflight:!0});else if(!gateState&&parsed.data.mode==="swarm-pr-feedback:verification")gateState=await activatePrWorkflow(directory,context.sessionID,"PR_FEEDBACK",{requireCheckoutPreflight:!0});if(gateState?.mode==="PR_REVIEW"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: active PR_REVIEW dispatch requires pr_head_sha");if(!verifiedReviewBaseSha||!parsed.data.base_ref)throw Error("BLOCKED: PR_REVIEW exact merge-base scope was not verified");gateState=await bindPrReviewBase(directory,context.sessionID,{prHeadSha:headSha,baseRef:parsed.data.base_ref,baseSha:verifiedReviewBaseSha});let laneSpecs=parsed.data.lanes.map((lane)=>({laneId:lane.id,workflowLane:lane.workflow_lane,reviewItemIds:lane.review_item_ids,ownedWorkflowLanes:lane.owned_workflow_lanes})),depthTier=gateState.prReviewDepthTier??"L";if(parsed.data.mode==="swarm-pr-review:base"){let configuredResilience=_internals260.loadPluginConfig(directory).pr_review_resilience??DEFAULT_PR_REVIEW_RESILIENCE_CONFIG,effectiveResilience=effectivePrReviewResilienceConfig(configuredResilience,gateState),contractRetry=parsed.data.pr_review_contract_retry===!0,waveStage=parsed.data.pr_review_wave_stage,waveAttempt=parsed.data.pr_review_wave_attempt;if(contractRetry&&(waveStage!==void 0||waveAttempt!==void 0))throw Error("BLOCKED: PR_REVIEW contract retry is mutually exclusive with pr_review_wave_stage and pr_review_wave_attempt");if(waveStage===void 0!==(waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW staged base dispatch requires both pr_review_wave_stage and pr_review_wave_attempt together");if(waveStage!==void 0&&waveAttempt!==void 0&&(!effectiveResilience.enabled||depthTier==="S"))throw Error("BLOCKED: staged PR_REVIEW base dispatch is valid only when pr_review_resilience is enabled at depth tier M or L");if(effectiveResilience.enabled&&depthTier!=="S"&&!contractRetry&&(waveStage===void 0||waveAttempt===void 0))throw Error("BLOCKED: PR_REVIEW base dispatch at depth tier M or L requires canary-first pr_review_wave_stage and pr_review_wave_attempt while pr_review_resilience is enabled");let stagedBaseDispatch=effectiveResilience.enabled&&depthTier!=="S"&&waveStage!==void 0&&waveAttempt!==void 0,effectiveMaxConcurrent=parsed.data.max_concurrent??parsed.data.lanes.length;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||effectiveMaxConcurrent!==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||effectiveMaxConcurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||effectiveMaxConcurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(effectiveMaxConcurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_internals260.createParallelDispatcher({enabled:!0,maxConcurrentTasks:maxConcurrent,evidenceLockTimeoutMs:0}),limit=pLimit(maxConcurrent);try{let laneResults=await Promise.all(lanes.map((lane)=>limit(()=>launchAsyncLane({session,dispatcher,lane,directory,timeoutMs:launchTimeoutMs,context,batchId,mode:parsed.data.mode,prHeadSha:parsed.data.pr_head_sha,gitHead:verifiedPrHead,dirtyHash:workflowRevisionDigest,scope:canonicalWorkflowScope,prReviewWorkflowInstanceId,prReviewWorkflowRevision}))));if(parsed.data.mode==="swarm-pr-review:base"&&context.sessionID?.trim()&&(parsed.data.pr_review_wave_stage!==void 0||parsed.data.pr_review_contract_retry===!0))try{await rollbackPrReviewBaseAdmissionIfUnlaunched(directory,context.sessionID,batchId,parsed.data.pr_review_contract_retry===!0)}catch(error93){throw log("pr-review base-admission rollback failed",{batchId,sessionID:context.sessionID,error:error93 instanceof Error?error93.message:String(error93)}),error93}let failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected"),pending=laneResults.filter((lane)=>lane.status==="pending");return{success:failed.length===0&&rejected2.length===0,batch_id:batchId,dispatched:laneResults.length,pending:pending.length,failed:failed.length,rejected:rejected2.length,max_concurrent:maxConcurrent,launch_timeout_ms:launchTimeoutMs,timeout_ms:launchTimeoutMs,lane_results:laneResults}}finally{dispatcher.shutdown()}}async function executeCollectLaneResults(args2,directory,context={}){let parsed=CollectLaneResultsArgsSchema.safeParse(args2);if(!parsed.success)return collectFailureResult({failure_class:"invalid_args",batch_id:"",message:"Invalid collect_lane_results arguments",errors:boundZodIssues(parsed.error.issues)});let timeoutMs=parsed.data.timeout_ms??DEFAULT_COLLECT_TIMEOUT_MS,deadline=_internals260.now()+timeoutMs,hostTimeouts=new Set,collectionResourceFailures=new Map,receiptAppendFailureLogs=new Set,settleFailureLogs=new Map,batchFilter=context.sessionID!==void 0?{parentSessionId:context.sessionID}:void 0,initialRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(initialRead.status==="uncertain")return collectFailureResult({failure_class:"store_unreadable",batch_id:parsed.data.batch_id,message:`Delegation store unreadable after ${initialRead.attempts} attempts; batch ${parsed.data.batch_id} is UNKNOWN, not absent (${initialRead.reason})`});let records=initialRead.value;if(records.length===0)return collectFailureResult({failure_class:"not_found",batch_id:parsed.data.batch_id,message:`No async lane batch found for ${parsed.data.batch_id}`});await recoverTerminalLaneReceipts(directory,records);let revisionSnapshots=new Map,session=_internals260.getSessionOps();if(!session||typeof session.messages!=="function"){let reviewReceiptFallbacks2=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result2=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks2}),observed=reducePrReviewEvent({sessionID:context.sessionID??"",revision:0},{type:"collection_observed",diagnostic:"host_unavailable",pendingLaneIds:records.filter((record3)=>!isTerminalDelegationStatus2(record3.status)).map((record3)=>record3.laneId??record3.correlationId)}),diagnosticCode=observed.status==="applied"?observed.effects.find((effect)=>effect.kind==="emit_diagnostic")?.code??"collection_host_unavailable":"collection_host_unavailable";return result2.failure_class="no_client",result2.message="OpenCode session messages client is not available; lane state is reported as stored and no lane was cancelled or terminalized. Poll again once the host client is available, cancel explicitly, or rely on the presumed-stale backstop.",result2.errors=[`OpenCode session messages client is not available (${diagnosticCode})`],await attachPendingLaneLiveness(result2,directory,records,deadline),result2}let keepPolling=!0,pollIntervalMs=COLLECT_POLL_INTERVAL_MS;while(keepPolling){await collectOnce(session,directory,records,parsed.data.cancel_pending===!0,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots),await sweepStaleAsyncLaneRecords(session,directory,records,DEFAULT_ASYNC_STALE_TIMEOUT_MS,deadline,hostTimeouts);let pollRead=findByBatchIdDetailed(directory,parsed.data.batch_id,batchFilter);if(pollRead.status==="uncertain"){if(addLaneDiagnostic(collectionResourceFailures,`batch:${parsed.data.batch_id}`,`collect re-read uncertain: delegation store unreadable after ${pollRead.attempts} attempts (${pollRead.reason}); settlement UNKNOWN, continuing to poll`),parsed.data.wait!==!0){keepPolling=!1;continue}}else if(records=pollRead.value,allSettled(records)||parsed.data.wait!==!0){keepPolling=!1;continue}if(_internals260.now()>=deadline){keepPolling=!1;continue}await _internals260.sleep(Math.min(pollIntervalMs,Math.max(0,deadline-_internals260.now()))),pollIntervalMs=nextCollectPollInterval(pollIntervalMs)}let reviewReceiptFallbacks=await resolvePrReviewReceiptFallbacks(directory,context.sessionID,records),result=buildCollectResult(parsed.data.batch_id,records,parsed.data.include_pending??parsed.data.wait!==!0,{directory,sessionID:context.sessionID,reviewReceipts:reviewReceiptFallbacks});if(await attachPendingLaneLiveness(result,directory,records,deadline),hostTimeouts.size>0)result.message=result.pending>0?"Collection deadline exhausted while waiting for OpenCode host calls; pending lanes remain safe to retry.":"Collection recovered and settled all lanes despite bounded OpenCode host-call timeouts; no collection retry is required.";let starvedProbeCount=(result.pending_liveness??[]).filter((lane)=>lane.degradedReason===PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON).length;if(starvedProbeCount>0)result.message=`${result.message?`${result.message} `:""}${starvedProbeCount} pending-liveness probe(s) skipped for budget (${PR_WORKFLOW_PROBE_SKIPPED_NO_BUDGET_REASON}); lanes may be further settled than reported.`;let diagnostics=assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures);if(diagnostics.length>0)result.errors=diagnostics;return result}async function attachPendingLaneLiveness(result,directory,records,deadline){if(result.pending<=0)return;let pendingLiveness=await collectPrWorkflowPendingLaneLiveness(directory,records,{probeBudgetMs:Math.max(0,deadline-_internals260.now())});if(pendingLiveness.length>0)result.pending_liveness=pendingLiveness}async function createLaneSession(args2){let generation=1,decision=args2.dispatcher.dispatch(args2.lane.id);while(!0){if(decision.action!=="dispatch")return{ok:!1,generation,error:`dispatcher ${decision.action}: ${decision.reason}`};let createTimeoutMessage=`Lane "${args2.lane.id}" session.create timed out after ${args2.timeoutMs}ms`,createPromise;try{createPromise=args2.session.create(buildLaneSessionCreateArgs(args2.directory,args2.lane,args2.context))}catch(error93){createPromise=Promise.reject(error93)}let createTimedOut=!1;createPromise.then((result)=>{if(createTimedOut&&result.data?.id)scheduleSessionCleanup(args2.session,result.data.id)}).catch(()=>{return});let failureSignal,failureMessage;try{let result=await withTimeout2(createPromise,args2.timeoutMs,createTimeoutMessage);if(result.data?.id)return{ok:!0,sessionId:result.data.id,generation,slotId:decision.slot.slotId,runId:decision.slot.runId};failureSignal=result.error,failureMessage=result.error===void 0||result.error===null?"session.create failed: malformed response without a session id":`session.create failed: ${formatError3(result.error)}`}catch(error93){if(failureSignal=error93,failureMessage=formatError3(error93),failureMessage===createTimeoutMessage)createTimedOut=!0}if((createTimedOut||isRetryableSessionCreateFailure(failureSignal))&&generation<MAX_SESSION_CREATE_GENERATIONS){args2.dispatcher.releaseSlot(decision.slot.slotId),generation++,decision=args2.dispatcher.dispatch(args2.lane.id);continue}return{ok:!1,error:failureMessage,generation,slotId:decision.slot.slotId,runId:decision.slot.runId}}}function isRetryableSessionCreateFailure(error93){if(error93===void 0||error93===null)return!1;let seen=new WeakSet,pending=[{value:error93,depth:0}],visited=0,signalChars=0,transient=!1,permanent=!1,truncated=!1;while(pending.length>0&&visited<MAX_CREATE_FAILURE_WALK_NODES){let current=pending.shift();visited++;let{value,depth,key:key2}=current;if((key2==="isRetryable"||key2==="retryable")&&value===!1)permanent=!0;if(typeof value==="number"&&Number.isInteger(value)){if(key2===void 0||CREATE_FAILURE_STATUS_KEYS.has(key2)){if(TRANSIENT_CREATE_STATUS_CODES.has(value))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(value))permanent=!0}continue}if(typeof value==="string"){if(key2!==void 0&&!CREATE_FAILURE_SCALAR_KEYS.has(key2))continue;if(key2!==void 0&&CREATE_FAILURE_STATUS_KEYS.has(key2)&&/^\d+$/.test(value)){let numericStatus=Number(value);if(TRANSIENT_CREATE_STATUS_CODES.has(numericStatus))transient=!0;if(PERMANENT_CREATE_STATUS_CODES.has(numericStatus))permanent=!0}let remaining=MAX_CREATE_FAILURE_SIGNAL_CHARS-signalChars;if(remaining<=0){truncated=!0;continue}let signal2=value.slice(0,remaining);if(signal2.length<value.length)truncated=!0;if(signalChars+=signal2.length,PERMANENT_CREATE_SIGNAL_PATTERN.test(signal2))permanent=!0;if(TRANSIENT_CREATE_SIGNAL_PATTERN.test(signal2))transient=!0;continue}if(typeof value!=="object"&&typeof value!=="function"||value===null)continue;let object3=value;if(seen.has(object3))continue;if(seen.add(object3),depth>=MAX_CREATE_FAILURE_WALK_DEPTH){truncated=!0;continue}let isArray=!1;try{isArray=Array.isArray(object3)}catch{truncated=!0;continue}if(isArray){let arrayLength;try{let lengthDescriptor=Object.getOwnPropertyDescriptor(object3,"length");if(!lengthDescriptor||!("value"in lengthDescriptor)||typeof lengthDescriptor.value!=="number"||!Number.isSafeInteger(lengthDescriptor.value)||lengthDescriptor.value<0){truncated=!0;continue}arrayLength=lengthDescriptor.value}catch{truncated=!0;continue}let remainingNodes=MAX_CREATE_FAILURE_WALK_NODES-visited,itemCount=Math.min(arrayLength,remainingNodes);if(itemCount<arrayLength)truncated=!0;for(let index=0;index<itemCount;index++){let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,index)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:key2})}continue}for(let propertyKey of CREATE_FAILURE_FIELD_KEYS){if(pending.length+visited>=MAX_CREATE_FAILURE_WALK_NODES){truncated=!0;break}let descriptor;try{descriptor=Object.getOwnPropertyDescriptor(object3,propertyKey)}catch{truncated=!0;continue}if(!descriptor)continue;if(!("value"in descriptor)){truncated=!0;continue}pending.push({value:descriptor.value,depth:depth+1,key:propertyKey})}}if(pending.length>0)truncated=!0;return transient&&!permanent&&!truncated}async function launchAsyncLane(args2){let validation2=validateLaneAgent(args2.lane.agent,args2.context),role=validation2.role,startedAt=isoNow2();if(!validation2.ok)return{id:args2.lane.id,agent:args2.lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let create=await createLaneSession({session:args2.session,dispatcher:args2.dispatcher,lane:args2.lane,directory:args2.directory,timeoutMs:args2.timeoutMs,context:args2.context});try{if(!create.ok)return failedLane(args2.lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);let sessionId=create.sessionId,legacyTranscriptCompatibility=args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"?prReviewLegacyTranscriptCompatibilityEnabled(_internals260.loadPluginConfig(args2.directory).pr_review_legacy_transcript_compatibility):void 0,pendingOutcome=await recordPendingDelegationDetailed(args2.directory,{correlationId:sessionId,jobId:args2.prReviewWorkflowInstanceId?encodePrReviewWorkflowBinding(args2.prReviewWorkflowInstanceId):null,subagentSessionId:sessionId,parentSessionId:args2.context.sessionID?.trim()||`dispatch_lanes_async:${args2.batchId}`,callID:args2.batchId,normalizedAgent:role,swarmPrefixedAgent:args2.lane.agent,planTaskId:null,evidenceTaskId:null,batchId:args2.batchId,laneId:args2.lane.id,mode:args2.mode??"advisory",workflowLane:args2.lane.workflow_lane,ownedWorkflowLanes:args2.lane.owned_workflow_lanes,prReviewLegacyTranscriptCompatibility:legacyTranscriptCompatibility,promptHash:promptHash(args2.lane,args2.directory,args2.batchId),workspace:{directory:args2.directory,gitHead:args2.gitHead??null,dirtyHash:args2.dirtyHash??null,prHeadSha:args2.prHeadSha??null,scope:args2.scope??null},...args2.prReviewWorkflowRevision!==void 0?{workflowGeneration:args2.prReviewWorkflowRevision}:{},generation:create.generation});if(pendingOutcome.status==="duplicate"||pendingOutcome.status==="conflict")return failedLane(args2.lane,role,startedAt,pendingOutcome.status==="duplicate"?"Async lane session.create returned an already-recorded correlation id":"Async lane session.create returned a correlation id owned by a different background delegation",create.slotId,create.runId,sessionId,create.generation);if(pendingOutcome.status==="failed")return cleanupAsyncLaunchSession(args2.session,sessionId),failedLane(args2.lane,role,startedAt,"Failed to record async lane in background delegation ledger",create.slotId,create.runId,sessionId,create.generation);return emitDelegationBegin(pendingOutcome.record),scheduleAsyncLanePrompt({session:args2.session,directory:args2.directory,sessionId,lane:args2.lane,timeoutMs:args2.timeoutMs,mode:args2.mode,structuredAdapter:args2.context.prReviewStructuredPromptAdapter}),{id:args2.lane.id,agent:args2.lane.agent,role,status:"pending",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2()}}catch(error93){return failedLane(args2.lane,role,startedAt,formatError3(error93),create.slotId,create.runId,create.ok?create.sessionId:void 0,create.generation)}finally{if(create.slotId)args2.dispatcher.releaseSlot(create.slotId)}}async function collectOnce(session,directory,records,cancelPending,deadline,hostTimeouts,receiptAppendFailureLogs,collectionResourceFailures,settleFailureLogs,revisionSnapshots){let activeRecords=records.filter((record3)=>record3.status==="pending"||record3.status==="running");if(activeRecords.length===0)return;let refreshLimit=pLimit(COLLECT_REFRESH_CONCURRENCY),fetchLaneRecord=async(record3)=>{let laneLabel=record3.laneId??record3.correlationId,needsRevisionDigest=Boolean(record3.workspace?.prHeadSha),laneBudgets=reserveConcurrentLaneCallBudgets(deadline,activeRecords.length,typeof session.status==="function",needsRevisionDigest);if(cancelPending){if(typeof session.abort==="function")try{await withCollectionDeadline(()=>session.abort({path:{id:record3.subagentSessionId}}),deadline,`session.abort for lane session "${record3.subagentSessionId}"`,hostTimeouts,laneBudgets.laneBudgetMs)}catch{let abortTimeoutPrefix=`session.abort for lane session "${record3.subagentSessionId}" exceeded`;if([...hostTimeouts].some((entry)=>entry.startsWith(abortTimeoutPrefix)))return{kind:"skipped"}}return await settleDelegationTerminal(directory,record3,{status:"cancelled",result:{error:"lane cancelled via collect_lane_results cancel_pending",chars:0,truncated:!1,digest:digestText2(""),workflowLaneFailureClass:"liveness"}},{},_internals260.now()),{kind:"skipped"}}let readiness=await getLaneCollectionReadiness(session,directory,record3.subagentSessionId,deadline,hostTimeouts,laneBudgets.statusBudgetMs);if(readiness==="busy")return{kind:"skipped"};try{let messages=await withCollectionDeadline(()=>session.messages({path:{id:record3.subagentSessionId},query:{directory,limit:ASYNC_MESSAGE_FETCH_LIMIT}}),deadline,`session.messages for lane "${laneLabel}"`,hostTimeouts,laneBudgets.messagesBudgetMs);return{kind:"fetched",readiness,messages,laneBudgets}}catch(error93){return{kind:"messages-error",error:error93}}},fetched=await Promise.all(activeRecords.map((record3)=>refreshLimit(()=>fetchLaneRecord(record3)))),pendingSettlements=[];for(let index=0;index<activeRecords.length;index++){let record3=activeRecords[index],laneLabel=record3.laneId??record3.correlationId,outcome=fetched[index];if(!outcome||outcome.kind==="skipped")continue;if(outcome.kind==="messages-error"){let messageTimeoutPrefix=`session.messages for lane "${laneLabel}" exceeded the remaining collect_lane_results budget`;if(![...hostTimeouts].some((entry)=>entry.startsWith(messageTimeoutPrefix)))addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages transport error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(outcome.error)}`);continue}let{readiness,messages,laneBudgets}=outcome;if(!messages.data){if(messages.error)addLaneDiagnostic(collectionResourceFailures,laneLabel,`session.messages returned an error for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(messages.error)}`);continue}clearLaneDiagnostics(collectionResourceFailures,laneLabel);let transcript=extractAssistantTranscript(messages.data),relyingOnCompletedAtOnly=readiness!=="idle"&&Number.isFinite(transcript.completedAt),hostSaysRetryable=transcript.terminalError?.kind!=="aborted"&&transcript.terminalError?.hostRetryable===!0;if(transcript.terminalError&&!transcript.text&&!transcript.windowTruncated&&(Number.isFinite(transcript.completedAt)||readiness==="idle")&&!(relyingOnCompletedAtOnly&&hostSaysRetryable)){let settledStatus=transcript.terminalError.kind==="aborted"?"cancelled":"error",reason=laneTerminalErrorReason(transcript.terminalError),settled=await settleDelegationTerminal(directory,record3,{status:settledStatus,result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),terminalErrorClass:terminalErrorClassFromLaneTerminalError(transcript.terminalError)}},{},_internals260.now());if(settled.kind==="claimed")clearLaneDiagnostics(settleFailureLogs,laneLabel),cleanupAsyncLaunchSession(session,record3.subagentSessionId);else if(isBenignSettleOutcome(settled.kind))clearLaneDiagnostics(settleFailureLogs,laneLabel);else if(settled.kind==="uncertain")addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle deferred for lane "${laneLabel}"; delegation store unreadable (${settled.reason??"unclassified"}); lane left open for retry`);else addLaneDiagnostic(settleFailureLogs,laneLabel,`terminal settle write did not land for lane "${laneLabel}"; lane left open`);continue}if(!transcript.text)continue;if(readiness==="unknown"&&!transcript.terminalAssistantProof)continue;pendingSettlements.push(settleCollectedLane({directory,record:record3,transcript,deadline,hostTimeouts,revisionDigestBudgetMs:laneBudgets.revisionDigestBudgetMs,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}))}await Promise.all(pendingSettlements)}function revisionSnapshotKey(directory,prHeadSha){return`${canonicalRootKeyFresh(directory)}\x00${prHeadSha??""}`}var MAX_DIAGNOSTICS_PER_LANE=3,MAX_HOST_TIMEOUT_DIAGNOSTICS=MAX_LANES*4,MAX_LANE_DIAGNOSTICS_PER_CHANNEL=MAX_LANES*MAX_DIAGNOSTICS_PER_LANE;function assembleCollectionDiagnostics(hostTimeouts,settleFailureLogs,collectionResourceFailures){return[...flattenLaneDiagnostics(settleFailureLogs),...flattenLaneDiagnostics(collectionResourceFailures),...[...hostTimeouts].slice(0,MAX_HOST_TIMEOUT_DIAGNOSTICS)]}function addLaneDiagnostic(diagnostics,laneLabel,message){let entries2=diagnostics.get(laneLabel);if(entries2===void 0)entries2=new Set,diagnostics.set(laneLabel,entries2);if(entries2.has(message))return;if(entries2.size>=MAX_DIAGNOSTICS_PER_LANE)return;entries2.add(message)}function clearLaneDiagnostics(diagnostics,laneLabel){diagnostics.delete(laneLabel)}function flattenLaneDiagnostics(diagnostics){let flat=[];for(let entries2 of diagnostics.values())for(let entry of entries2){if(flat.length>=MAX_LANE_DIAGNOSTICS_PER_CHANNEL)return flat;flat.push(entry)}return flat}var MAX_DIAGNOSTIC_CAUSE_CHARS=160;function safeDiagnosticCause(error93){let redacted=sanitizeFailureEvidenceDisplay(formatError3(error93));if(redacted.length===0)return"(no detail)";return redacted.length>MAX_DIAGNOSTIC_CAUSE_CHARS?`${redacted.slice(0,MAX_DIAGNOSTIC_CAUSE_CHARS)}…`:redacted}function resolveCollectExpectedWorkflowIdentity(record3,parentState){if(record3.mode!=="swarm-pr-review:base"&&record3.mode!=="swarm-pr-review:micro"&&record3.mode!=="swarm-pr-review:council")return;let workflowInstanceId=decodePrReviewWorkflowBinding(record3.jobId),workflowRevision=record3.workflowGeneration;if(!workflowInstanceId||workflowRevision===void 0)return;if(!parentState||parentState.mode!=="PR_REVIEW")return;if(parentState.workflowInstanceId!==workflowInstanceId)return;let baseSha=parentState.prReviewBaseSha;if(!baseSha)return;return{workflowInstanceId,workflowRevision,baseSha}}async function settleCollectedLane(args2){let{directory,record:record3,transcript,deadline,hostTimeouts,receiptAppendFailureLogs,revisionSnapshots,settleFailureLogs}=args2,laneLabel=record3.laneId??record3.correlationId,collectedRevisionDigest,prHeadSha=record3.workspace?.prHeadSha;if(prHeadSha)try{let key2=revisionSnapshotKey(directory,prHeadSha),snapshot2=revisionSnapshots.get(key2);if(snapshot2===void 0){snapshot2=_internals260.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha);let pending=snapshot2;pending.catch(()=>{if(revisionSnapshots.get(key2)===pending)revisionSnapshots.delete(key2)}),revisionSnapshots.set(key2,pending)}let shared=snapshot2;collectedRevisionDigest=await withCollectionDeadline(()=>shared,deadline,`revision digest for lane "${laneLabel}"`,hostTimeouts,args2.revisionDigestBudgetMs)??void 0}catch(error93){addLaneDiagnostic(settleFailureLogs,laneLabel,`revision snapshot unavailable for lane "${laneLabel}"; lane left pending: ${safeDiagnosticCause(error93)}`);return}clearLaneDiagnostics(settleFailureLogs,laneLabel);let output=prepareLaneOutput({directory,batchId:record3.batchId??record3.callID,laneId:record3.laneId??record3.correlationId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,sessionId:record3.subagentSessionId,parentSessionId:record3.parentSessionId,mode:record3.mode,workflowLane:record3.workflowLane,prHeadSha:record3.workspace?.prHeadSha??void 0,gitHead:record3.workspace?.gitHead??void 0,revisionDigest:collectedRevisionDigest,scope:record3.workspace?.scope??void 0,source:"collect_lane_results",text:transcript.text,messageCount:transcript.messageCount,transcriptIncomplete:transcript.transcriptIncomplete}),prospectiveResult={text:output.output,chars:output.output_chars,truncated:output.output_truncated,digest:output.output_digest,...output.output_ref?{outputRef:output.output_ref}:{},outputPreviewChars:output.output.length,...output.output_degraded!==void 0?{outputDegraded:output.output_degraded}:{},...output.output_artifact_error?{outputArtifactError:output.output_artifact_error}:{},...output.transcript_incomplete!==void 0?{transcriptIncomplete:output.transcript_incomplete}:{},messageCount:transcript.messageCount,...record3.result?.prReviewResultReceipt?{prReviewResultReceipt:record3.result.prReviewResultReceipt}:{}},terminalStatus="completed";if(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"||record3.mode==="swarm-pr-review:council"){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,collectExpectedIdentity;if(record3.parentSessionId?.trim())try{let parentState=await readPrWorkflowGateStateFromDisk(directory,record3.parentSessionId.trim());collectExpectedIdentity=resolveCollectExpectedWorkflowIdentity(record3,parentState)}catch{collectExpectedIdentity=void 0}let validation2=validatePrReviewDiscoveryLaneCompletion2({record:record3,result:prospectiveResult,artifact,expected:{mode:record3.mode,workflowLane:record3.workflowLane??"",ownedWorkflowLanes:record3.ownedWorkflowLanes,prHeadSha:record3.workspace?.prHeadSha??"",gitHead:record3.workspace?.gitHead??"",revisionDigest:collectedRevisionDigest??"",reviewScope:record3.workspace?.scope??void 0,...collectExpectedIdentity??{}}});if(validation2.ok&&validation2.salvaged?.length){if(prospectiveResult.salvagedWorkflowLanes=[...validation2.salvaged],validation2.recoveries?.length)prospectiveResult.salvagedWorkflowLaneRecoveries=[...validation2.recoveries]}if(!validation2.ok){terminalStatus="error",prospectiveResult.workflowLaneFailureClass="contract";let family=record3.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane";prospectiveResult.error=`PR_REVIEW_DISCOVERY_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${formatPrReviewLaneValidationFailure(validation2.failure)}; expected candidate row: ${CANDIDATE_HEADERS[family]}; expected clean row: ${CLEAN_TEMPLATES[family]}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}}let isPrReviewVerdictLane=record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic";if((isPrReviewVerdictLane||record3.mode==="swarm-pr-feedback:verification"||record3.mode==="swarm-pr-feedback:stage-b-reviewer"||record3.mode==="swarm-pr-feedback:stage-b-test"||record3.mode==="swarm-pr-feedback:closeout-reviewer"||record3.mode==="swarm-pr-feedback:closeout-critic")&&(isPrReviewVerdictLane||prospectiveResult.truncated===!0||prospectiveResult.transcriptIncomplete===!0)){let artifact=output.output_ref?readLaneOutput(directory,output.output_ref)?.artifact??null:null,transportValidationOperation=`transport recovery validation for lane "${record3.laneId??record3.correlationId}"`,transportValidationDeadlineDiagnosticPrefix=`${transportValidationOperation} exceeded the remaining collect_lane_results budget (`,validation2;try{validation2=await withCollectionDeadline(()=>_internals260.validatePrWorkflowTransportRecovery({directory,record:record3,result:prospectiveResult,artifact,revisionDigest:collectedRevisionDigest??""}),deadline,transportValidationOperation,hostTimeouts)}catch(error93){if(formatError3(error93).startsWith(transportValidationDeadlineDiagnosticPrefix))return;terminalStatus="error",prospectiveResult.error=`PR_WORKFLOW_CONTRACT_INVALID: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} `+formatError3(error93),prospectiveResult.error=prospectiveResult.error.slice(0,1024),await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{},_internals260.now());return}if(validation2.receipt){let resultWithReceipt=appendPrReviewCollectionReceipt(record3,prospectiveResult,validation2.receipt);if(!resultWithReceipt){if(consumePrReviewReceiptAppendFailureLog(receiptAppendFailureLogs,record3.parentSessionId,record3.correlationId))log(`[dispatch-lanes] withheld PR-review terminal result without receipt: correlation=${record3.correlationId} batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"}`);return}prospectiveResult=resultWithReceipt}if(!validation2.ok){terminalStatus="error";let errorCode3=validation2.failure?.predicate==="reviewer.verdict_rows"||validation2.failure?.predicate==="critic.verdict_rows"?"PR_REVIEW_VERDICT_CONTRACT_INVALID":"PR_WORKFLOW_CONTRACT_INVALID";prospectiveResult.error=`${errorCode3}: batch=${record3.batchId??"(missing)"} lane=${record3.laneId??"(missing)"} workflow_lane=${record3.workflowLane??"(missing)"} ${validation2.reason}`,prospectiveResult.error=prospectiveResult.error.slice(0,1024)}else if(validation2.recoveries?.length){let workflowLane=record3.workflowLane?.trim();if(workflowLane)prospectiveResult.salvagedWorkflowLanes=[workflowLane];prospectiveResult.salvagedWorkflowLaneRecoveries=[...prospectiveResult.salvagedWorkflowLaneRecoveries??[],...validation2.recoveries]}}await settleDelegationTerminal(directory,record3,{status:terminalStatus,result:prospectiveResult},{transcript:transcript.text,startedAt:record3.createdAt,model:laneConfiguredModel(record3)},_internals260.now())}function laneConfiguredModel(record3){let prefixed=record3.swarmPrefixedAgent,baseRole=stripKnownSwarmPrefix(prefixed),swarmID=baseRole!==prefixed?prefixed.slice(0,prefixed.length-baseRole.length-1):void 0;return getSwarmAgents(swarmID)?.[baseRole]?.model}function consumePrReviewReceiptAppendFailureLog(loggedFailures,parentSessionId,correlationId){let key2=`${parentSessionId}\x00${correlationId}`;if(loggedFailures.has(key2))return!1;return loggedFailures.add(key2),!0}class LanePromptLaunchRejectionError extends Error{constructor(message){super(message);this.name="LanePromptLaunchRejectionError"}}function scheduleAsyncLanePrompt(args2){queueMicrotask(()=>{startAsyncLanePrompt(args2).catch(async(error93)=>{let message=formatError3(error93);await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,message)})})}async function startAsyncLanePrompt(args2){if(args2.structuredAdapter&&(args2.mode==="swarm-pr-review:base"||args2.mode==="swarm-pr-review:micro"))try{await withTimeout2(args2.structuredAdapter.promptJsonSchema({sessionId:args2.sessionId,agent:args2.lane.agent,schema:exports_external.toJSONSchema(PrReviewLaneResultEnvelopeSchema),parts:[{type:"text",text:args2.lane.prompt}]}),args2.timeoutMs,`Lane "${args2.lane.id}" structured PR-review launch timed out after ${args2.timeoutMs}ms`);return}catch(error93){if(!(error93 instanceof PrReviewStructuredPromptUnsupportedError)){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}}let promptController=new AbortController,baseRole=stripKnownSwarmPrefix(args2.lane.agent),swarmID=baseRole!==args2.lane.agent?args2.lane.agent.slice(0,args2.lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),lanePrimaryModel=swarmAgents?.[baseRole]?.model,laneFallbackModels=swarmAgents?.[baseRole]?.fallback_models??[],registry4=_internals260.getGeneratedAgentNames();if(registry4.length>0&&!registry4.some((name)=>name.toLowerCase()===args2.lane.agent.toLowerCase())&&!swarmAgents?.[baseRole]&&!lanePrimaryModel&&laneFallbackModels.length===0){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`Lane "${args2.lane.id}" agent "${args2.lane.agent}" resolves no registered swarm agent and no model; refusing to launch a lane the host cannot run`);return}let promptResult;try{promptResult=(await dispatchWithModelFallback({dispatch:async(model,context)=>{let result=await withTimeout2(args2.session.promptAsync({path:{id:args2.sessionId},query:{directory:args2.directory},body:{agent:args2.lane.agent,...model?{model}:{},tools:buildReadOnlyTools(args2.mode),parts:[{type:"text",text:args2.lane.prompt}]},signal:promptController.signal}),context.remainingMs??args2.timeoutMs,`Lane "${args2.lane.id}" session.promptAsync launch timed out after ${context.remainingMs??args2.timeoutMs}ms`,promptController);if(result.error)throw new LanePromptLaunchRejectionError(`session.promptAsync launch failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals260.now()+args2.timeoutMs,now:_internals260.now,scope:{sessionID:args2.sessionId,invocationID:`dispatch-lanes-async:${args2.lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result}catch(error93){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,formatError3(error93));return}if(promptResult.error){await appendAsyncLaneLaunchError(args2.directory,args2.session,args2.sessionId,`session.promptAsync launch failed: ${formatError3(promptResult.error)}`);return}await appendDelegationTransition(args2.directory,args2.sessionId,{status:"running"})}async function appendAsyncLaneLaunchError(directory,session,sessionId,message){let recordRead=findByCorrelationIdDetailed(directory,sessionId);if(recordRead.status==="uncertain"){warnDelegationReadUncertainOnce2(`launch-error settle skipped for lane session ${sessionId}`,recordRead),cleanupAsyncLaunchSession(session,sessionId);return}let record3=recordRead.value,launchErrorResult={error:message,chars:message.length,truncated:!1,digest:digestText2(message),workflowLaneFailureClass:"resource"};if(record3)await settleDelegationTerminal(directory,record3,{status:"error",result:launchErrorResult},{},_internals260.now());else await appendDelegationTransition(directory,sessionId,{status:"error",result:launchErrorResult,terminalResult:buildTypedDelegationTerminal({correlationId:sessionId,jobId:null},"error",launchErrorResult,_internals260.now())});cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";try{let status2=await withCollectionDeadline(()=>session.status({query:{directory}}),deadline,`session.status for lane session "${sessionId}"`,hostTimeouts,statusBudgetMs);if(status2.error||!status2.data)return"unknown";let current=status2.data[sessionId];if(current===void 0)return"unknown";if(current.type==="idle")return"idle";if(current.type==="busy"||current.type==="retry")return"busy";return"unknown"}catch{return"unknown"}}var DELEGATION_READ_UNCERTAIN_LOG_LIMIT2=64,delegationReadUncertainLogged2=new Set;function warnDelegationReadUncertainOnce2(label,uncertain){let key2=`${label}\x00${uncertain.reason}`;if(delegationReadUncertainLogged2.has(key2))return;if(delegationReadUncertainLogged2.size>=DELEGATION_READ_UNCERTAIN_LOG_LIMIT2){let oldest=delegationReadUncertainLogged2.values().next().value;if(oldest!==void 0)delegationReadUncertainLogged2.delete(oldest)}delegationReadUncertainLogged2.add(key2),warn(`${label}: delegation store unreadable after ${uncertain.attempts} attempts (${uncertain.reason}); skipping this pass`)}var SWEEP_LIVENESS_SETTLE_BUDGET_MS=250;async function sweepStaleAsyncLaneRecords(session,directory,records,staleTimeoutMs,deadline,hostTimeouts){if(staleTimeoutMs<=0)return;let now2=_internals260.now(),settleReserveMs=Math.min(SWEEP_LIVENESS_SETTLE_BUDGET_MS,Math.max(0,deadline-now2));for(let record3 of records){let currentBeforeReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentBeforeReadiness)continue;let statusBudgetMs=reserveCollectionLaneCallBudgets(deadline,records.length,typeof session.status==="function").statusBudgetMs;if(!(typeof session.status!=="function"||settleReserveMs>0&&deadline-_internals260.now()>0))continue;let readiness=await getLaneCollectionReadiness(session,directory,currentBeforeReadiness.subagentSessionId,deadline,hostTimeouts,Math.max(statusBudgetMs,settleReserveMs));if(readiness==="busy")continue;if(readiness==="unknown"){let currentUnknown=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentUnknown)continue;if(currentUnknown.result)continue;let reason=`lane ${currentUnknown.laneId??currentUnknown.correlationId} presumed dead: host session unobservable`;await settleDelegationTerminal(directory,currentUnknown,{status:"error",result:{error:reason,chars:reason.length,truncated:!1,digest:digestText2(reason),workflowLaneFailureClass:"liveness"}},{},_internals260.now());continue}let currentAfterReadiness=getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2);if(!currentAfterReadiness)continue;let idleStaleReason=`lane ${currentAfterReadiness.laneId??currentAfterReadiness.correlationId} presumed stale: idle host session past the stale horizon`,idleLivenessResult=currentAfterReadiness.result?{...currentAfterReadiness.result,workflowLaneFailureClass:"liveness"}:{error:idleStaleReason,chars:idleStaleReason.length,truncated:!1,digest:digestText2(idleStaleReason),workflowLaneFailureClass:"liveness"},idleTerminal=buildTypedDelegationTerminal(currentAfterReadiness,"stale",idleLivenessResult,_internals260.now());await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",result:idleLivenessResult,expectedCurrentStatuses:["pending","running","ingestion_error"],terminalResult:idleTerminal})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&¤t.status!=="running"&¤t.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),status2=error93.statusCode===void 0?"":` status=${error93.statusCode}`,retryable=error93.hostRetryable===void 0?"":` host_retryable=${error93.hostRetryable}`;return`${error93.category}: ${message} [kind=${error93.kind} name=${error93.name}${status2}${retryable}]`}function terminalErrorClassFromLaneTerminalError(error93){let category=error93.category.trim().length>0?error93.category.trim().slice(0,128):"unknown";return{kind:error93.kind,category,...error93.statusCode===void 0?{}:{statusCode:error93.statusCode},...error93.hostRetryable===void 0?{}:{hostRetryable:error93.hostRetryable}}}function readErrorDataRecord(error93){if(typeof error93!=="object"||error93===null)return{};let data=error93.data;return typeof data==="object"&&data!==null?data:{}}function classifyLaneTerminalError(error93){let name=typeof error93?.name==="string"?error93.name.slice(0,64):"UnknownError",data=readErrorDataRecord(error93),topLevelMessage=error93?.message,rawMessage=typeof data.message==="string"&&data.message.trim().length>0?data.message:typeof topLevelMessage==="string"&&topLevelMessage.trim().length>0?topLevelMessage:typeof error93==="string"&&error93.trim().length>0?error93:name,statusCode=typeof data.statusCode==="number"&&Number.isFinite(data.statusCode)?data.statusCode:void 0,hostRetryable=typeof data.isRetryable==="boolean"?data.isRetryable:void 0,kind=name==="MessageAbortedError"?"aborted":name==="MessageOutputLengthError"?"output_length":name==="APIError"||name==="ProviderAuthError"?"provider":"unknown",classified=classifyProviderFailure(statusCode===void 0?rawMessage:{message:rawMessage,status:statusCode}),category=kind==="aborted"?"provider.cancelled":classified.category;return{kind,name,message:classified.evidence.display,statusCode:statusCode??classified.evidence.statusCode,hostRetryable,category}}function extractAssistantTranscript(messages){let assistantTexts=[],lastAssistantInfo;for(let message of messages){if(message.info?.role!=="assistant")continue;lastAssistantInfo=message.info;let text=extractText3(message.parts);if(text.trim().length>0)assistantTexts.push(text)}let completedAt=lastAssistantInfo?.time?.completed,finish=typeof lastAssistantInfo?.finish==="string"?lastAssistantInfo.finish.toLowerCase():"",terminalAssistantFinish=finish==="stop"||finish==="length"||finish==="content-filter";return{text:assistantTexts.join(`
|
|
7632
7632
|
|
|
7633
|
-
`),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT||finish==="length"||finish==="content-filter",terminalAssistantProof:typeof completedAt==="number"&&Number.isFinite(completedAt)&&terminalAssistantFinish&&lastAssistantInfo?.error===void 0,completedAt:typeof completedAt==="number"?completedAt:void 0,windowTruncated:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT,terminalError:lastAssistantInfo?.error===void 0?void 0:classifyLaneTerminalError(lastAssistantInfo.error)}}function reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,hasStatusCall,hasRevisionDigestCall=!1){let remainingMs2=Math.max(0,deadline-_internals260.now());if(remainingMs2===0)return{laneBudgetMs:0,statusBudgetMs:0,messagesBudgetMs:0,revisionDigestBudgetMs:0};let laneBudgetMs=Math.min(remainingMs2,Math.max(1,Math.floor(remainingMs2/Math.max(1,remainingLaneCount)))),callCount=1+Number(hasStatusCall)+Number(hasRevisionDigestCall),statusBudgetMs=hasStatusCall?Math.min(MAX_STATUS_CALL_BUDGET_MS,Math.floor(laneBudgetMs/callCount)):0,afterStatusMs=laneBudgetMs-statusBudgetMs,revisionDigestBudgetMs=hasRevisionDigestCall?Math.floor(afterStatusMs/2):0;return{laneBudgetMs,statusBudgetMs,messagesBudgetMs:afterStatusMs-revisionDigestBudgetMs,revisionDigestBudgetMs}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2(),syncClassifiedReason;if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0,lifecycleRecordPromise=Promise.resolve(null);try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let createdSessionId=sessionId;lifecycleRecordPromise=recordPendingDelegationDetailed(directory,{correlationId:createdSessionId,jobId:null,subagentSessionId:createdSessionId,parentSessionId:context.sessionID?.trim()||`dispatch_lanes:${createdSessionId}`,callID:`blocking:${createdSessionId}`,normalizedAgent:role,swarmPrefixedAgent:lane.agent,planTaskId:null,evidenceTaskId:null,laneId:lane.id,mode:"blocking",promptHash:promptHash(lane,directory,`blocking:${createdSessionId}`),workspace:{directory,gitHead:null,dirtyHash:null,prHeadSha:null,scope:null},generation:create.generation}).then((pendingOutcome)=>{if(pendingOutcome.status==="recorded")return emitDelegationBegin(pendingOutcome.record),pendingOutcome.record;return log(`[dispatch-lanes] blocking lane start record did not land (status ${pendingOutcome.status}); lane ${lane.id} proceeds without durable lifecycle`),null});let baseRole=stripKnownSwarmPrefix(lane.agent),swarmID=baseRole!==lane.agent?lane.agent.slice(0,lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult=(await dispatchWithModelFallback({dispatch:async(model,context2)=>{syncClassifiedReason=void 0;let result=await withTimeout2(session.prompt({path:{id:createdSessionId},body:{agent:lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),context2.remainingMs??timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${context2.remainingMs??timeoutMs}ms`,promptController);if(!result.data)throw syncClassifiedReason=`session.prompt failed: ${laneTerminalErrorReason(classifyLaneTerminalError(result.error))}`,new LanePromptLaunchRejectionError(`session.prompt failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals260.now()+timeoutMs,now:_internals260.now,scope:{sessionID:sessionId,invocationID:`dispatch-lanes-sync:${lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result;if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)}),lifecycleRecord=await lifecycleRecordPromise;if(lifecycleRecord)await settleDelegationTerminal(directory,lifecycleRecord,{status:"completed",result:{text:laneOutput.output,chars:laneOutput.output_chars,truncated:laneOutput.output_truncated,digest:laneOutput.output_digest,...laneOutput.output_ref?{outputRef:laneOutput.output_ref}:{}}},{transcript:laneOutput.output,startedAt:Date.parse(startedAt)||void 0,model:swarmAgents?.[baseRole]?.model},_internals260.now());return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){let lifecycleRecord=await lifecycleRecordPromise.catch(()=>null);if(lifecycleRecord){let failureReason=syncClassifiedReason??formatError3(error93);await settleDelegationTerminal(directory,lifecycleRecord,{status:"error",result:{error:failureReason.slice(0,MAX_ERROR_CHARS),chars:failureReason.length,truncated:failureReason.length>MAX_ERROR_CHARS,digest:digestText2(failureReason)}},{startedAt:Date.parse(startedAt)||void 0},_internals260.now())}return failedLane(lane,role,startedAt,syncClassifiedReason??formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected2.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected2.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending,deliveryContext){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId,deliveryContext)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed"),pendingLanes=pending.map((record3)=>({batch_id:batchId,lane_id:record3.laneId??record3.correlationId,status:record3.status,...record3.result?.outputRef?{output_ref:record3.result.outputRef}:{}}));return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults,...pendingLanes.length>0?{pending_lanes:pendingLanes}:{}}}async function resolvePrReviewReceiptFallbacks(directory,sessionID,records){let receipts=new Map;if(!sessionID)return receipts;let unresolved=records.filter((record3)=>(record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic")&&!parsePrReviewCollectionReceipt(record3)&&record3.result!==void 0&&parsePrReviewCollectionReceiptShedMarker(record3,record3.result)!==null);if(unresolved.length===0)return receipts;let state2;try{state2=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return log(`[dispatch-lanes] unable to reconstruct compacted PR-review receipts: ${formatError3(error93)}`),receipts}if(!state2||state2.mode!=="PR_REVIEW")return receipts;return resolvePrReviewReceiptFallbacksFromState(unresolved,state2)}function resolvePrReviewReceiptFallbacksFromState(records,state2){let receipts=new Map;for(let record3 of records){let phase=record3.mode==="swarm-pr-review:reviewer"?"reviewer":record3.mode==="swarm-pr-review:critic"?"critic":null;if(!phase||!record3.batchId||!record3.laneId)continue;if(record3.status!=="completed"&&record3.status!=="error"&&record3.status!=="ingestion_error"&&record3.status!=="cancelled"&&record3.status!=="stale")continue;let itemIds=(state2.prReviewValidationBatches??[]).find((batch)=>batch.batchId===record3.batchId&&batch.phase===phase)?.lanes.find((candidate2)=>candidate2.laneId===record3.laneId&&candidate2.workflowLane===record3.workflowLane)?.reviewItemIds??[];if(itemIds.length===0)continue;let marker=record3.result?parsePrReviewCollectionReceiptShedMarker(record3,record3.result):null,projected=marker?projectPrReviewCollectionReceiptShedMarker(marker,itemIds):null;if(projected)receipts.set(record3.correlationId,projected)}return receipts}function appendPrReviewCollectionReceipt(record3,result,receipt){let sanitizedPreview=(result.text??"").split(/\r?\n/).filter((line)=>!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)&&!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)).join(`
|
|
7633
|
+
`),messageCount:assistantTexts.length,transcriptIncomplete:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT||finish==="length"||finish==="content-filter",terminalAssistantProof:typeof completedAt==="number"&&Number.isFinite(completedAt)&&terminalAssistantFinish&&lastAssistantInfo?.error===void 0,completedAt:typeof completedAt==="number"?completedAt:void 0,windowTruncated:messages.length>=ASYNC_MESSAGE_FETCH_LIMIT,terminalError:lastAssistantInfo?.error===void 0?void 0:classifyLaneTerminalError(lastAssistantInfo.error)}}function reserveCollectionLaneCallBudgets(deadline,remainingLaneCount,hasStatusCall,hasRevisionDigestCall=!1){let remainingMs2=Math.max(0,deadline-_internals260.now());if(remainingMs2===0)return{laneBudgetMs:0,statusBudgetMs:0,messagesBudgetMs:0,revisionDigestBudgetMs:0};let laneBudgetMs=Math.min(remainingMs2,Math.max(1,Math.floor(remainingMs2/Math.max(1,remainingLaneCount)))),callCount=1+Number(hasStatusCall)+Number(hasRevisionDigestCall),statusBudgetMs=hasStatusCall?Math.min(MAX_STATUS_CALL_BUDGET_MS,Math.floor(laneBudgetMs/callCount)):0,afterStatusMs=laneBudgetMs-statusBudgetMs,revisionDigestBudgetMs=hasRevisionDigestCall?Math.floor(afterStatusMs/2):0;return{laneBudgetMs,statusBudgetMs,messagesBudgetMs:afterStatusMs-revisionDigestBudgetMs,revisionDigestBudgetMs}}var MIN_CONCURRENT_LANE_BUDGET_MS=1000,COLLECT_REFRESH_CONCURRENCY=4;function reserveConcurrentLaneCallBudgets(deadline,laneCount,hasStatusCall,hasRevisionDigestCall=!1){let remainingMs2=Math.max(0,deadline-_internals260.now());if(remainingMs2===0)return{laneBudgetMs:0,statusBudgetMs:0,messagesBudgetMs:0,revisionDigestBudgetMs:0};let laneBudgetMs=Math.min(remainingMs2,Math.max(MIN_CONCURRENT_LANE_BUDGET_MS,Math.floor(remainingMs2/Math.max(1,laneCount)))),callCount=1+Number(hasStatusCall)+Number(hasRevisionDigestCall),statusBudgetMs=hasStatusCall?Math.min(MAX_STATUS_CALL_BUDGET_MS,Math.floor(laneBudgetMs/callCount)):0,afterStatusMs=laneBudgetMs-statusBudgetMs,revisionDigestBudgetMs=hasRevisionDigestCall?Math.floor(afterStatusMs/2):0;return{laneBudgetMs,statusBudgetMs,messagesBudgetMs:afterStatusMs-revisionDigestBudgetMs,revisionDigestBudgetMs}}function nextCollectPollInterval(currentMs){if(currentMs<=0)return COLLECT_POLL_INTERVAL_MS;return Math.min(currentMs*2,MAX_COLLECT_POLL_INTERVAL_MS)}async function runLane(session,dispatcher,lane,directory,timeoutMs,context){let validation2=validateLaneAgent(lane.agent,context),role=validation2.role,startedAt=isoNow2(),syncClassifiedReason;if(!validation2.ok)return{id:lane.id,agent:lane.agent,role,status:"rejected",started_at:startedAt,completed_at:isoNow2(),error:validation2.error};let promptController=new AbortController,create=await createLaneSession({session,dispatcher,lane,directory,timeoutMs,context}),sessionId=create.ok?create.sessionId:void 0,lifecycleRecordPromise=Promise.resolve(null);try{if(!create.ok)return failedLane(lane,role,startedAt,create.error,create.slotId,create.runId,void 0,create.generation);sessionId=create.sessionId;let createdSessionId=sessionId;lifecycleRecordPromise=recordPendingDelegationDetailed(directory,{correlationId:createdSessionId,jobId:null,subagentSessionId:createdSessionId,parentSessionId:context.sessionID?.trim()||`dispatch_lanes:${createdSessionId}`,callID:`blocking:${createdSessionId}`,normalizedAgent:role,swarmPrefixedAgent:lane.agent,planTaskId:null,evidenceTaskId:null,laneId:lane.id,mode:"blocking",promptHash:promptHash(lane,directory,`blocking:${createdSessionId}`),workspace:{directory,gitHead:null,dirtyHash:null,prHeadSha:null,scope:null},generation:create.generation}).then((pendingOutcome)=>{if(pendingOutcome.status==="recorded")return emitDelegationBegin(pendingOutcome.record),pendingOutcome.record;return log(`[dispatch-lanes] blocking lane start record did not land (status ${pendingOutcome.status}); lane ${lane.id} proceeds without durable lifecycle`),null});let baseRole=stripKnownSwarmPrefix(lane.agent),swarmID=baseRole!==lane.agent?lane.agent.slice(0,lane.agent.length-baseRole.length-1):void 0,swarmAgents=getSwarmAgents(swarmID),promptResult=(await dispatchWithModelFallback({dispatch:async(model,context2)=>{syncClassifiedReason=void 0;let result=await withTimeout2(session.prompt({path:{id:createdSessionId},body:{agent:lane.agent,...model?{model}:{},tools:buildReadOnlyTools(),parts:[{type:"text",text:lane.prompt}]},signal:promptController.signal}),context2.remainingMs??timeoutMs,`Lane "${lane.id}" session.prompt timed out after ${context2.remainingMs??timeoutMs}ms`,promptController);if(!result.data)throw syncClassifiedReason=`session.prompt failed: ${laneTerminalErrorReason(classifyLaneTerminalError(result.error))}`,new LanePromptLaunchRejectionError(`session.prompt failed: ${formatError3(result.error)}`);return result},classify:(error93)=>{if(!(error93 instanceof LanePromptLaunchRejectionError))return"permanent";return isTransientProviderError(error93.message)?"transient":"permanent"},maxTransientRetriesPerModel:0,deadlineAtMs:_internals260.now()+timeoutMs,now:_internals260.now,scope:{sessionID:sessionId,invocationID:`dispatch-lanes-sync:${lane.id}`,swarmID,role:baseRole},primaryModel:swarmAgents?.[baseRole]?.model,fallbackModels:swarmAgents?.[baseRole]?.fallback_models??[]})).result;if(!promptResult.data)return failedLane(lane,role,startedAt,`session.prompt failed: ${formatError3(promptResult.error)}`,create.slotId,create.runId,sessionId,create.generation);let laneOutput=prepareLaneOutput({directory,batchId:`blocking:${sessionId}`,laneId:lane.id,agent:lane.agent,role,sessionId,parentSessionId:context.sessionID,source:"dispatch_lanes",text:extractText3(promptResult.data.parts)}),lifecycleRecord=await lifecycleRecordPromise;if(lifecycleRecord)await settleDelegationTerminal(directory,lifecycleRecord,{status:"completed",result:{text:laneOutput.output,chars:laneOutput.output_chars,truncated:laneOutput.output_truncated,digest:laneOutput.output_digest,...laneOutput.output_ref?{outputRef:laneOutput.output_ref}:{}}},{transcript:laneOutput.output,startedAt:Date.parse(startedAt)||void 0,model:swarmAgents?.[baseRole]?.model},_internals260.now());return{id:lane.id,agent:lane.agent,role,status:"completed",session_id:sessionId,slot_id:create.slotId,run_id:create.runId,generation:create.generation,started_at:startedAt,completed_at:isoNow2(),...laneOutput}}catch(error93){let lifecycleRecord=await lifecycleRecordPromise.catch(()=>null);if(lifecycleRecord){let failureReason=syncClassifiedReason??formatError3(error93);await settleDelegationTerminal(directory,lifecycleRecord,{status:"error",result:{error:failureReason.slice(0,MAX_ERROR_CHARS),chars:failureReason.length,truncated:failureReason.length>MAX_ERROR_CHARS,digest:digestText2(failureReason)}},{startedAt:Date.parse(startedAt)||void 0},_internals260.now())}return failedLane(lane,role,startedAt,syncClassifiedReason??formatError3(error93),create.slotId,create.runId,sessionId,create.generation)}finally{if(create.slotId)dispatcher.releaseSlot(create.slotId);if(promptController.abort(),sessionId)scheduleSessionCleanup(session,sessionId)}}function buildResult(laneResults,maxConcurrent,timeoutMs){let completed=laneResults.filter((lane)=>lane.status==="completed"),failed=laneResults.filter((lane)=>lane.status==="failed"),rejected2=laneResults.filter((lane)=>lane.status==="rejected");return{success:failed.length===0&&rejected2.length===0,dispatched:laneResults.length,completed:completed.length,failed:failed.length,rejected:rejected2.length,max_concurrent:maxConcurrent,timeout_ms:timeoutMs,lane_results:laneResults}}function buildCollectResult(batchId,records,includePending,deliveryContext){let laneResults=records.filter((record3)=>includePending||record3.status!=="pending"&&record3.status!=="running"&&record3.status!=="ingesting").map((record3)=>recordToLaneResult(record3,batchId,deliveryContext)),completed=records.filter((record3)=>record3.status==="completed"),failed=records.filter((record3)=>record3.status==="error"||record3.status==="ingestion_error"),cancelled=records.filter((record3)=>record3.status==="cancelled"),stale=records.filter((record3)=>record3.status==="stale"),pending=records.filter((record3)=>record3.status==="pending"||record3.status==="running"||record3.status==="ingesting"),consumed=records.filter((record3)=>record3.status==="consumed"),pendingLanes=pending.map((record3)=>({batch_id:batchId,lane_id:record3.laneId??record3.correlationId,status:record3.status,...record3.result?.outputRef?{output_ref:record3.result.outputRef}:{}}));return{success:pending.length===0&&failed.length===0&&cancelled.length===0&&stale.length===0,batch_id:batchId,total:records.length,completed:completed.length,failed:failed.length,cancelled:cancelled.length,stale:stale.length,pending:pending.length,consumed:consumed.length,all_settled:pending.length===0,lane_results:laneResults,...pendingLanes.length>0?{pending_lanes:pendingLanes}:{}}}async function resolvePrReviewReceiptFallbacks(directory,sessionID,records){let receipts=new Map;if(!sessionID)return receipts;let unresolved=records.filter((record3)=>(record3.mode==="swarm-pr-review:reviewer"||record3.mode==="swarm-pr-review:critic")&&!parsePrReviewCollectionReceipt(record3)&&record3.result!==void 0&&parsePrReviewCollectionReceiptShedMarker(record3,record3.result)!==null);if(unresolved.length===0)return receipts;let state2;try{state2=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return log(`[dispatch-lanes] unable to reconstruct compacted PR-review receipts: ${formatError3(error93)}`),receipts}if(!state2||state2.mode!=="PR_REVIEW")return receipts;return resolvePrReviewReceiptFallbacksFromState(unresolved,state2)}function resolvePrReviewReceiptFallbacksFromState(records,state2){let receipts=new Map;for(let record3 of records){let phase=record3.mode==="swarm-pr-review:reviewer"?"reviewer":record3.mode==="swarm-pr-review:critic"?"critic":null;if(!phase||!record3.batchId||!record3.laneId)continue;if(record3.status!=="completed"&&record3.status!=="error"&&record3.status!=="ingestion_error"&&record3.status!=="cancelled"&&record3.status!=="stale")continue;let itemIds=(state2.prReviewValidationBatches??[]).find((batch)=>batch.batchId===record3.batchId&&batch.phase===phase)?.lanes.find((candidate2)=>candidate2.laneId===record3.laneId&&candidate2.workflowLane===record3.workflowLane)?.reviewItemIds??[];if(itemIds.length===0)continue;let marker=record3.result?parsePrReviewCollectionReceiptShedMarker(record3,record3.result):null,projected=marker?projectPrReviewCollectionReceiptShedMarker(marker,itemIds):null;if(projected)receipts.set(record3.correlationId,projected)}return receipts}function appendPrReviewCollectionReceipt(record3,result,receipt){let sanitizedPreview=(result.text??"").split(/\r?\n/).filter((line)=>!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)&&!line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)).join(`
|
|
7634
7634
|
`),footer=encodePrReviewCollectionReceiptFooter(record3,result,receipt)??encodePrReviewCollectionReceiptShedMarkerFromReceipt(record3,result,receipt);if(!footer)return null;let text=sanitizedPreview?`${sanitizedPreview}
|
|
7635
|
-
${footer}`:footer;return{...result,text,outputPreviewChars:text.length}}function parsePrReviewCollectionReceipt(record3){if(!record3.result)return null;let payload=parsePrReviewCollectionReceiptFooter(record3,record3.result);return payload?projectPrReviewCollectionReceipt(payload):null}function recordToLaneResult(record3,batchId,deliveryContext){let status2=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"||record3.status==="ingesting"?"pending":record3.status,laneId=record3.laneId??record3.correlationId,digest5=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1,reviewReceipt=parsePrReviewCollectionReceipt(record3)??deliveryContext?.reviewReceipts?.get(record3.correlationId);if(record3.result?.text!==void 0&&status2!=="pending"&&digest5&&outputRef){let key2=`${batchId}\x00${laneId}\x00${digest5}`;if(alreadyDelivered=hasLaneOutputBeenDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2),!alreadyDelivered)markLaneOutputDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2)}return{id:laneId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status:status2,session_id:record3.subagentSessionId,generation:record3.generation??1,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{...alreadyDelivered?{output_omitted_repeat:!0}:{output:record3.result.text},output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{},...record3.result.workflowLaneFailureClass!==void 0?{workflow_lane_failure_class:record3.result.workflowLaneFailureClass}:{},...record3.result.salvagedWorkflowLanes?.length?{salvaged_workflow_lanes:[...record3.result.salvagedWorkflowLanes]}:{},...record3.result.salvagedWorkflowLaneRecoveries?.length?{salvaged_workflow_lane_recoveries:record3.result.salvagedWorkflowLaneRecoveries.map((recovery)=>({workflow_lane:recovery.workflowLane,kind:recovery.kind,reason:recovery.reason}))}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{},...reviewReceipt?{accepted_review_item_ids:[...reviewReceipt.acceptedReviewItemIds],rejected_review_item_ids:[...reviewReceipt.rejectedReviewItemIds]}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId,generation){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,generation,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals260.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};if(generatedAgentNames.length>0){let normalized=agent.toLowerCase();if(!generatedAgentNames.find((name)=>name.toLowerCase()===normalized)){let shown=generatedAgentNames.slice(0,8).join(", "),overflow=generatedAgentNames.length>8?`, and ${generatedAgentNames.length-8} more`:"";return{ok:!1,role,error:`Agent "${agent}" is not registered on this host. Registered generated agent names: ${shown}${overflow}. Use a registered name (bare canonical roles are only valid when the host registers them).`}}}let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(mode){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;if(tools.write=!1,tools.edit=!1,tools.patch=!1,mode==="swarm-pr-review:base"||mode==="swarm-pr-review:micro")for(let toolName of PR_REVIEW_CHILD_AGENT_TOOL_MAP.explorer??[])tools[toolName]=!0;return tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult2(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}var ORIENTATION_SUFFIX_RESERVE_CHARS=5000;async function augmentCommonPromptWithOrientation(directory,lanes,commonPrompt,orientation,sessionID,deps){if(orientation===!1)return commonPrompt;let buildBlock=deps?.buildBlock??buildLaneOrientationBlock,block=null;try{block=await buildBlock(directory,lanes.map((lane)=>lane.prompt),sessionID?{sessionID}:void 0)}catch(error93){return log("lane orientation block failed open",{error:error93 instanceof Error?error93.message:String(error93)}),commonPrompt}if(!block)return commonPrompt;let combined=commonPrompt?`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${block}`:block;if(lanes.some((lane)=>combined.length+COMMON_PROMPT_SEPARATOR.length+lane.prompt.length+ORIENTATION_SUFFIX_RESERVE_CHARS>MAX_PROMPT_CHARS))return log("lane orientation block dropped: combined common_prompt + orientation + lane prompt + suffix reserve would exceed MAX_PROMPT_CHARS",{maxPromptChars:MAX_PROMPT_CHARS,blockChars:block.length}),commonPrompt;return combined}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes,options={}){let generatedAgentNames=_internals260.getGeneratedAgentNames(),errors5=[],formatted=lanes.map((lane)=>{let role=resolveGeneratedAgentRole(lane.agent,generatedAgentNames),isPrReviewCouncilExplorer=options.mode==="swarm-pr-review:council"&&role.startsWith("council_");if(role!=="explorer"&&!isPrReviewCouncilExplorer)return lane;let isPrReviewDiscovery=options.mode==="swarm-pr-review:base"||options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer,rowFamilyIdentity=options.mode==="swarm-pr-review:base"?"For this base explorer lane, use the base row family and put the exact workflow_lane only in the `lane` field.":options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?"For this micro/council lane, use the micro row family and put the exact workflow_lane only in the `micro_lane` field; do not use the base `lane` field.":"Use the row family applicable to this dispatch and put the exact workflow_lane only in that family's `lane` or `micro_lane` field.",exactLaneInput=lane.workflow_lane??lane.id,exactLaneResult=classifyControllerTokenField(exactLaneInput);if(!exactLaneResult.ok){let reason=exactLaneResult.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" workflow_lane ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned,index)=>({index,result:classifyControllerTokenField(owned)})):[{index:0,result:exactLaneResult}],invalidOwnedLane=ownedLaneResults.find(({result})=>!result.ok);if(invalidOwnedLane){let reason=!invalidOwnedLane.result.ok&&invalidOwnedLane.result.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" owned_workflow_lanes[${invalidOwnedLane.index}] ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLanes=ownedLaneResults.map(({result})=>result.ok?result.token:""),identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,formatSuffix=options.mode==="swarm-pr-review:base"?BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX:options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX:EXPLORER_CANDIDATE_FORMAT_SUFFIX,controllerIdentity=`CONTROLLER-BOUND OUTPUT IDENTITY: ${identity}. Placeholder text such as "workflow_lane" is invalid. ${rowFamilyIdentity}`,embeddedKnownSuffixes=[EXPLORER_CANDIDATE_FORMAT_SUFFIX,BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX,MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX].filter((suffix)=>lane.prompt.includes(suffix)),expectedSuffixOccurrences=lane.prompt.split(formatSuffix).length-1,isControllerOwnedIdempotent=lane.prompt.endsWith(formatSuffix)&&lane.prompt.includes(controllerIdentity)&&embeddedKnownSuffixes.length===1&&expectedSuffixOccurrences===1,controllerIdentityStart=lane.prompt.lastIndexOf(controllerIdentity,lane.prompt.length-formatSuffix.length),operatorPrompt=isControllerOwnedIdempotent?`${lane.prompt.slice(0,controllerIdentityStart)}${lane.prompt.slice(controllerIdentityStart+controllerIdentity.length,-formatSuffix.length)}`.trimEnd():lane.prompt,rejectForbiddenPrReviewOperatorPrompt=(prompt2)=>{if(!isPrReviewDiscovery)return!1;let encouragesVerbatimShellQuoting=/(?:\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b.{0,80}\b(?:faithfully|verbatim|exactly|literally)\b|\b(?:faithfully|verbatim|exactly|literally)\b.{0,80}\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b)/i.test(prompt2),forbidden=[prompt2.includes(CANDIDATE_HEADERS.base_explorer)?"the canonical base discovery header":null,prompt2.includes(CANDIDATE_HEADERS.micro_lane)?"the canonical micro discovery header":null,/\[CANDIDATE\]/.test(prompt2)?"[CANDIDATE]":null,/\[CLEAN\]/.test(prompt2)?"[CLEAN]":null,encouragesVerbatimShellQuoting?"verbatim shell or pipeline quoting guidance":null].find((value)=>value!==null);if(!forbidden)return!1;return errors5.push(`Lane "${lane.id}" operator prompt contains ${forbidden}; PR-review discovery prompts carry content only and the controller injects the authoritative output contract`),!0};if(isControllerOwnedIdempotent)return rejectForbiddenPrReviewOperatorPrompt(operatorPrompt),lane;if(embeddedKnownSuffixes.length>0){let diagnostic=`Lane "${lane.id}" prompt contains an incompatible, duplicate, or controller-unbound explorer output contract for mode "${options.mode??"generic"}"`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}if(rejectForbiddenPrReviewOperatorPrompt(lane.prompt))return lane;let prompt=`${lane.prompt}
|
|
7635
|
+
${footer}`:footer;return{...result,text,outputPreviewChars:text.length}}function parsePrReviewCollectionReceipt(record3){if(!record3.result)return null;let payload=parsePrReviewCollectionReceiptFooter(record3,record3.result);return payload?projectPrReviewCollectionReceipt(payload):null}function recordToLaneResult(record3,batchId,deliveryContext){let status2=record3.status==="error"?"failed":record3.status==="ingestion_error"?"failed":record3.status==="running"||record3.status==="ingesting"?"pending":record3.status,laneId=record3.laneId??record3.correlationId,digest5=record3.result?.digest,outputRef=record3.result?.outputRef?.trim(),alreadyDelivered=!1,reviewReceipt=parsePrReviewCollectionReceipt(record3)??deliveryContext?.reviewReceipts?.get(record3.correlationId);if(record3.result?.text!==void 0&&status2!=="pending"&&digest5&&outputRef){let key2=`${batchId}\x00${laneId}\x00${digest5}`;if(alreadyDelivered=hasLaneOutputBeenDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2),!alreadyDelivered)markLaneOutputDelivered(deliveryContext?.directory,deliveryContext?.sessionID,key2)}return{id:laneId,agent:record3.swarmPrefixedAgent,role:record3.normalizedAgent,status:status2,session_id:record3.subagentSessionId,generation:record3.generation??1,started_at:new Date(record3.createdAt).toISOString(),completed_at:new Date(record3.completedAt??record3.updatedAt).toISOString(),...record3.result?.text!==void 0?{...alreadyDelivered?{output_omitted_repeat:!0}:{output:record3.result.text},output_chars:record3.result.chars,output_truncated:record3.result.truncated,output_digest:record3.result.digest,...record3.result.outputRef?{output_ref:record3.result.outputRef}:{},...record3.result.outputPreviewChars!==void 0?{output_preview_chars:record3.result.outputPreviewChars}:{},...record3.result.outputDegraded!==void 0?{output_degraded:record3.result.outputDegraded}:{},...record3.result.outputArtifactError?{output_artifact_error:record3.result.outputArtifactError}:{},...record3.result.transcriptIncomplete!==void 0?{transcript_incomplete:record3.result.transcriptIncomplete}:{},...record3.result.messageCount!==void 0?{message_count:record3.result.messageCount}:{},...record3.result.workflowLaneFailureClass!==void 0?{workflow_lane_failure_class:record3.result.workflowLaneFailureClass}:{},...record3.result.salvagedWorkflowLanes?.length?{salvaged_workflow_lanes:[...record3.result.salvagedWorkflowLanes]}:{},...record3.result.salvagedWorkflowLaneRecoveries?.length?{salvaged_workflow_lane_recoveries:record3.result.salvagedWorkflowLaneRecoveries.map((recovery)=>({workflow_lane:recovery.workflowLane,kind:recovery.kind,reason:recovery.reason}))}:{}}:{},...record3.result?.error!==void 0?{error:record3.result.error}:{},...reviewReceipt?{accepted_review_item_ids:[...reviewReceipt.acceptedReviewItemIds],rejected_review_item_ids:[...reviewReceipt.rejectedReviewItemIds]}:{}}}function allSettled(records){return records.every((record3)=>record3.status!=="pending"&&record3.status!=="running")}function failedLane(lane,role,startedAt,error93,slotId,runId,sessionId,generation){return{id:lane.id,agent:lane.agent,role,status:"failed",session_id:sessionId,slot_id:slotId,run_id:runId,generation,started_at:startedAt,completed_at:isoNow2(),error:error93}}function validateLaneAgent(agent,context){let generatedAgentNames=_internals260.getGeneratedAgentNames(),role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return{ok:!1,role,error:`Agent "${agent}" is not registered as a generated swarm agent or canonical role`};if(!READ_ONLY_LANE_ROLES.has(role))return{ok:!1,role,error:`Agent role "${role}" is not allowed for read-only lane dispatch`};if(generatedAgentNames.length>0){let normalized=agent.toLowerCase();if(!generatedAgentNames.find((name)=>name.toLowerCase()===normalized)){let shown=generatedAgentNames.slice(0,8).join(", "),overflow=generatedAgentNames.length>8?`, and ${generatedAgentNames.length-8} more`:"";return{ok:!1,role,error:`Agent "${agent}" is not registered on this host. Registered generated agent names: ${shown}${overflow}. Use a registered name (bare canonical roles are only valid when the host registers them).`}}}let callerPrefix=context.callerAgent?getGeneratedAgentPrefix(context.callerAgent,generatedAgentNames):null;if(callerPrefix){if(getGeneratedAgentPrefix(agent,generatedAgentNames)!==callerPrefix)return{ok:!1,role,error:`Agent "${agent}" does not match caller swarm prefix "${callerPrefix}"`}}return{ok:!0,role}}function getGeneratedAgentPrefix(agent,generatedAgentNames){let role=resolveGeneratedAgentRole(agent,generatedAgentNames);if(!isKnownCanonicalRole(role))return null;let normalized=agent.toLowerCase();if(normalized===role)return null;for(let separator of AGENT_NAME_SEPARATORS){let suffix=`${separator}${role}`;if(normalized.endsWith(suffix))return normalized.slice(0,-suffix.length)}return null}function buildReadOnlyTools(mode){let tools={};for(let toolName of READ_ONLY_TOOL_DENYLIST)tools[toolName]=!1;if(tools.write=!1,tools.edit=!1,tools.patch=!1,mode==="swarm-pr-review:base"||mode==="swarm-pr-review:micro")for(let toolName of PR_REVIEW_CHILD_AGENT_TOOL_MAP.explorer??[])tools[toolName]=!0;return tools}function prepareLaneOutput(args2){let stored=storeLaneOutput(args2.directory,{batchId:args2.batchId,laneId:args2.laneId,agent:args2.agent,role:args2.role,sessionId:args2.sessionId,parentSessionId:args2.parentSessionId,mode:args2.mode,workflowLane:args2.workflowLane,prHeadSha:args2.prHeadSha,gitHead:args2.gitHead,revisionDigest:args2.revisionDigest,scope:args2.scope,source:args2.source,text:args2.text,messageCount:args2.messageCount,transcriptIncomplete:args2.transcriptIncomplete}),preview=buildLaneOutputPreview({text:args2.text,ref:stored.ref,degraded:stored.degraded,maxChars:MAX_LANE_OUTPUT_CHARS});return{...preview,output_ref:stored.ref,output_digest:stored.digest,output_preview_chars:preview.output.length,...stored.degraded?{output_degraded:!0}:{},...stored.error?{output_artifact_error:stored.error}:{},...args2.transcriptIncomplete!==void 0?{transcript_incomplete:args2.transcriptIncomplete}:{},...args2.messageCount!==void 0?{message_count:args2.messageCount}:{}}}function failureResult2(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,dispatched:0,completed:0,failed:0,rejected:0,max_concurrent:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function asyncFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:null,dispatched:0,pending:0,failed:0,rejected:0,max_concurrent:0,launch_timeout_ms:0,timeout_ms:0,lane_results:[],errors:args2.errors}}function collectFailureResult(args2){return{success:!1,failure_class:args2.failure_class,message:args2.message,batch_id:args2.batch_id,total:0,completed:0,failed:0,cancelled:0,stale:0,pending:0,consumed:0,all_settled:!1,lane_results:[],errors:args2.errors}}var ORIENTATION_SUFFIX_RESERVE_CHARS=5000;async function augmentCommonPromptWithOrientation(directory,lanes,commonPrompt,orientation,sessionID,deps){if(orientation===!1)return commonPrompt;let buildBlock=deps?.buildBlock??buildLaneOrientationBlock,block=null;try{block=await buildBlock(directory,lanes.map((lane)=>lane.prompt),sessionID?{sessionID}:void 0)}catch(error93){return log("lane orientation block failed open",{error:error93 instanceof Error?error93.message:String(error93)}),commonPrompt}if(!block)return commonPrompt;let combined=commonPrompt?`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${block}`:block;if(lanes.some((lane)=>combined.length+COMMON_PROMPT_SEPARATOR.length+lane.prompt.length+ORIENTATION_SUFFIX_RESERVE_CHARS>MAX_PROMPT_CHARS))return log("lane orientation block dropped: combined common_prompt + orientation + lane prompt + suffix reserve would exceed MAX_PROMPT_CHARS",{maxPromptChars:MAX_PROMPT_CHARS,blockChars:block.length}),commonPrompt;return combined}function applyCommonPrompt(lanes,commonPrompt){if(!commonPrompt)return{ok:!0,lanes:[...lanes]};let errors5=[],merged=lanes.map((lane)=>{let prompt=`${commonPrompt}${COMMON_PROMPT_SEPARATOR}${lane.prompt}`;if(prompt.length>MAX_PROMPT_CHARS)errors5.push(`Lane "${lane.id}" combined common_prompt + prompt is ${prompt.length} chars (common_prompt ${commonPrompt.length} + separator ${COMMON_PROMPT_SEPARATOR.length} + lane prompt ${lane.prompt.length}; max ${MAX_PROMPT_CHARS})`);return{...lane,prompt}});if(errors5.length>0)return{ok:!1,errors:errors5};return{ok:!0,lanes:merged}}function applyExplorerFormatSuffix(lanes,options={}){let generatedAgentNames=_internals260.getGeneratedAgentNames(),errors5=[],formatted=lanes.map((lane)=>{let role=resolveGeneratedAgentRole(lane.agent,generatedAgentNames),isPrReviewCouncilExplorer=options.mode==="swarm-pr-review:council"&&role.startsWith("council_");if(role!=="explorer"&&!isPrReviewCouncilExplorer)return lane;let isPrReviewDiscovery=options.mode==="swarm-pr-review:base"||options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer,rowFamilyIdentity=options.mode==="swarm-pr-review:base"?"For this base explorer lane, use the base row family and put the exact workflow_lane only in the `lane` field.":options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?"For this micro/council lane, use the micro row family and put the exact workflow_lane only in the `micro_lane` field; do not use the base `lane` field.":"Use the row family applicable to this dispatch and put the exact workflow_lane only in that family's `lane` or `micro_lane` field.",exactLaneInput=lane.workflow_lane??lane.id,exactLaneResult=classifyControllerTokenField(exactLaneInput);if(!exactLaneResult.ok){let reason=exactLaneResult.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" workflow_lane ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned,index)=>({index,result:classifyControllerTokenField(owned)})):[{index:0,result:exactLaneResult}],invalidOwnedLane=ownedLaneResults.find(({result})=>!result.ok);if(invalidOwnedLane){let reason=!invalidOwnedLane.result.ok&&invalidOwnedLane.result.reason==="multiple"?"must be exactly one token after controller sanitization":"must not be empty after controller sanitization",diagnostic=`Lane "${lane.id}" owned_workflow_lanes[${invalidOwnedLane.index}] ${reason}`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}let ownedLanes=ownedLaneResults.map(({result})=>result.ok?result.token:""),identity=ownedLanes.length===1?`every output row MUST use the exact lane value "${ownedLanes[0]}"`:`this consolidated lane covers ${ownedLanes.length} obligations — evaluate EVERY one and emit a distinct [CANDIDATE] row set or fully populated [CLEAN] attestation for EACH of: ${ownedLanes.map((owned)=>`"${owned}"`).join(", ")}; every output row MUST use the exact lane value of the obligation it reports`,formatSuffix=options.mode==="swarm-pr-review:base"?BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX:options.mode==="swarm-pr-review:micro"||isPrReviewCouncilExplorer?MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX:EXPLORER_CANDIDATE_FORMAT_SUFFIX,controllerIdentity=`CONTROLLER-BOUND OUTPUT IDENTITY: ${identity}. Placeholder text such as "workflow_lane" is invalid. ${rowFamilyIdentity}`,embeddedKnownSuffixes=[EXPLORER_CANDIDATE_FORMAT_SUFFIX,BASE_EXPLORER_CANDIDATE_FORMAT_SUFFIX,MICRO_EXPLORER_CANDIDATE_FORMAT_SUFFIX].filter((suffix)=>lane.prompt.includes(suffix)),expectedSuffixOccurrences=lane.prompt.split(formatSuffix).length-1,isControllerOwnedIdempotent=lane.prompt.endsWith(formatSuffix)&&lane.prompt.includes(controllerIdentity)&&embeddedKnownSuffixes.length===1&&expectedSuffixOccurrences===1,controllerIdentityStart=lane.prompt.lastIndexOf(controllerIdentity,lane.prompt.length-formatSuffix.length),operatorPrompt=isControllerOwnedIdempotent?`${lane.prompt.slice(0,controllerIdentityStart)}${lane.prompt.slice(controllerIdentityStart+controllerIdentity.length,-formatSuffix.length)}`.trimEnd():lane.prompt,rejectForbiddenPrReviewOperatorPrompt=(prompt2)=>{if(!isPrReviewDiscovery)return!1;let encouragesVerbatimShellQuoting=/(?:\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b.{0,80}\b(?:faithfully|verbatim|exactly|literally)\b|\b(?:faithfully|verbatim|exactly|literally)\b.{0,80}\b(?:quote|copy|transcribe|reproduce)\b.{0,80}\b(?:pipeline|shell|command|text)\b)/i.test(prompt2),forbidden=[prompt2.includes(CANDIDATE_HEADERS.base_explorer)?"the canonical base discovery header":null,prompt2.includes(CANDIDATE_HEADERS.micro_lane)?"the canonical micro discovery header":null,/\[CANDIDATE\]/.test(prompt2)?"[CANDIDATE]":null,/\[CLEAN\]/.test(prompt2)?"[CLEAN]":null,encouragesVerbatimShellQuoting?"verbatim shell or pipeline quoting guidance":null].find((value)=>value!==null);if(!forbidden)return!1;return errors5.push(`Lane "${lane.id}" operator prompt contains ${forbidden}; PR-review discovery prompts carry content only and the controller injects the authoritative output contract. Remove the format/template text from the lane prompt and retry — the controller appends the authoritative contract automatically.`),!0};if(isControllerOwnedIdempotent)return rejectForbiddenPrReviewOperatorPrompt(operatorPrompt),lane;if(embeddedKnownSuffixes.length>0){let diagnostic=`Lane "${lane.id}" prompt contains an incompatible, duplicate, or controller-unbound explorer output contract for mode "${options.mode??"generic"}"`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: ${diagnostic}; preserving the caller prompt for generic compatibility`),lane}if(rejectForbiddenPrReviewOperatorPrompt(lane.prompt))return lane;let prompt=`${lane.prompt}
|
|
7636
7636
|
|
|
7637
7637
|
${controllerIdentity}${formatSuffix}`;if(prompt.length>MAX_PROMPT_CHARS){let diagnostic=`Lane "${lane.id}" prompt plus mandatory explorer output contract is ${prompt.length} chars; max ${MAX_PROMPT_CHARS} (a repo-graph orientation block may have been prepended to common_prompt — retry with orientation: false to exclude it)`;if(options.failClosed)return errors5.push(diagnostic),lane;return log(`[dispatch-lanes] applyExplorerFormatSuffix: lane "${lane.id}" prompt too long (${lane.prompt.length} chars + suffix = ${prompt.length}, max ${MAX_PROMPT_CHARS}); `+"format enforcement skipped — explorer may not emit [CANDIDATE] rows"),lane}return{...lane,prompt}});return errors5.length>0?{ok:!1,errors:errors5}:{ok:!0,lanes:formatted}}function prReviewLaneResponseBudgetChars(mode,lane){if(mode==="swarm-pr-review:base")return PR_REVIEW_BASE_LANE_RESPONSE_BUDGET_CHARS;if(mode==="swarm-pr-review:micro"){let owned=Math.max(1,lane.owned_workflow_lanes?.length??1);return Math.min(PR_REVIEW_RESPONSE_BUDGET_CEILING_CHARS,PR_REVIEW_MICRO_LANE_RESPONSE_BUDGET_CHARS+(owned-1)*PR_REVIEW_MICRO_PER_OWNED_LANE_CHARS)}if(mode==="swarm-pr-review:council")return PR_REVIEW_COUNCIL_LANE_RESPONSE_BUDGET_CHARS;if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let items=Math.max(0,lane.review_item_ids?.length??0);return Math.min(PR_REVIEW_RESPONSE_BUDGET_CEILING_CHARS,PR_REVIEW_VERDICT_RESPONSE_FLOOR_CHARS+items*PR_REVIEW_VERDICT_RESPONSE_PER_ITEM_CHARS)}return}function applyPrWorkflowPromptContract(lanes,options){let mode=options.mode;if(!mode?.startsWith("swarm-pr-review:")&&!mode?.startsWith("swarm-pr-feedback:"))return{ok:!0,lanes:[...lanes]};if(!options.prHeadSha||!options.revisionDigest)return{ok:!1,errors:["PR workflow prompts require controller-verified head and revision bindings"]};let errors5=[],contracted=lanes.map((lane)=>{let normalizedMode=classifyControllerTokenField(mode),workflowLane=classifyControllerTokenField(lane.workflow_lane??""),prHeadSha=classifyControllerTokenField(options.prHeadSha??""),revisionDigest=classifyControllerTokenField(options.revisionDigest??""),batchId=classifyControllerTokenField(options.batchId??""),laneId=classifyControllerTokenField(lane.id),requiresSettlementProvenance=options.batchId!==void 0&&normalizedMode.ok&&(normalizedMode.token==="swarm-pr-review:base"||normalizedMode.token==="swarm-pr-review:micro"),declaredScope=canonicalizeControllerField(options.scope??"the exact checked-out PR revision and repository-defined diff context"),callerFocus=canonicalizeControllerField(options.callerFocus??""),assignedIdResults=(lane.review_item_ids??lane.feedback_item_ids??[]).map((itemId)=>classifyControllerTokenField(itemId)),invalidAssignedId=assignedIdResults.find((result)=>!result.ok);if(!normalizedMode.ok||!prHeadSha.ok||!revisionDigest.ok||requiresSettlementProvenance&&(!batchId.ok||!laneId.ok))return errors5.push(`Lane "${lane.id}" mandatory PR workflow contract requires non-empty single-token mode, pr_head_sha, revision_digest, and (for base/micro lanes) batch/lane provenance after controller sanitization`),lane;if(!workflowLane.ok&&workflowLane.reason==="multiple")return errors5.push(`Lane "${lane.id}" workflow_lane must be exactly one token after controller sanitization`),lane;if(invalidAssignedId)return errors5.push(`Lane "${lane.id}" assigned_item_ids must contain exactly one token per item after controller sanitization`),lane;let fallbackChecklist=normalizedMode.token.endsWith(":reviewer")?"re-read every assigned candidate at its exact location; prove classification, reachability, mitigation, severity, and falsification path":normalizedMode.token.endsWith(":critic")?"challenge every assigned verdict for evidence, reachability, mitigation, severity, coherence, and required report changes":"inspect the bound scope using the complete repository-defined contract for this lane",ownedLaneResults=lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes.map((owned)=>classifyControllerTokenField(owned)):void 0;if(ownedLaneResults?.find((result)=>!result.ok))return errors5.push(`Lane "${lane.id}" owned_workflow_lanes must contain exactly one token per item after controller sanitization`),lane;let ownedLanes=ownedLaneResults?.map((result)=>result.ok?result.token:""),assignedIds=assignedIdResults.map((result)=>result.ok?result.token:""),checklist=ownedLanes?ownedLanes.map((owned)=>`[${owned}] ${PR_WORKFLOW_LANE_CHECKLISTS[owned]??fallbackChecklist}`).join(" "):PR_WORKFLOW_LANE_CHECKLISTS[workflowLane.ok?workflowLane.token:""]??fallbackChecklist,ownedLine=ownedLanes?`
|
|
7638
7638
|
owned_workflow_lanes: ${ownedLanes.join(", ")} — every owned obligation requires its own [CANDIDATE] rows or fully populated [CLEAN] attestation naming that obligation`:"",responseBudget=prReviewLaneResponseBudgetChars(normalizedMode.token,lane),budgetLine=responseBudget!==void 0?`
|
|
@@ -7779,7 +7779,7 @@ ${content}
|
|
|
7779
7779
|
|
|
7780
7780
|
### Mutation Coverage Gap
|
|
7781
7781
|
- **[${finding.severity}]** \`${finding.location}\` (${finding.category}) — ${finding.detail}
|
|
7782
|
-
_Evidence:_ ${finding.evidence}`}init_zod();init_pr_review_contract();init_pr_workflow_gate();init_create_tool();var SubmitPrReviewResultArgsSchema=exports_external.object({schemaVersion:exports_external.literal(1),batchId:exports_external.string().trim().min(1).max(120).optional(),laneId:exports_external.string().trim().min(1).max(120).optional(),revisionDigest:exports_external.string().trim().regex(/^[0-9a-f]{64}$/i),result:PrReviewLaneResultEnvelopeSchema}).strict();async function executeSubmitPrReviewResult(args2,directory,context={}){let parsed=SubmitPrReviewResultArgsSchema.safeParse(args2),childSessionId=context.sessionID?.trim();if(!childSessionId)return JSON.stringify({success:!1,message:"submit_pr_review_result requires an authenticated child session"});if(!parsed.success)
|
|
7782
|
+
_Evidence:_ ${finding.evidence}`}init_zod();init_pr_review_contract();init_pr_workflow_gate();init_canonical_root();init_create_tool();var SubmitPrReviewResultArgsSchema=exports_external.object({schemaVersion:exports_external.preprocess((value)=>value==="1"?1:value,exports_external.literal(1)).describe('the JSON number 1 (the string "1" is also accepted)'),batchId:exports_external.string().trim().min(1).max(120).optional(),laneId:exports_external.string().trim().min(1).max(120).optional(),revisionDigest:exports_external.string().trim().regex(/^[0-9a-f]{64}$/i),result:PrReviewLaneResultEnvelopeSchema}).strict(),RECEIVED_VALUE_RENDER_LIMIT=120,MAX_FORMATTED_ISSUE_MESSAGE_CHARS=2000;function resolveReceivedValue(args2,path358){let current=args2;for(let key2 of path358){if(current===null||typeof current!=="object")return;current=current[key2]}return current}function renderReceivedValue(value){let typeofLabel=typeof value;if(value===void 0)return"received undefined";let rendered;try{rendered=JSON.stringify(value)??"null"}catch{return`received <unrepresentable> (${typeofLabel})`}if(rendered.length>RECEIVED_VALUE_RENDER_LIMIT)rendered=`${rendered.slice(0,RECEIVED_VALUE_RENDER_LIMIT)}…`;return`received ${rendered} (${typeofLabel})`}var UNRECOGNIZED_KEY_PATTERN=/Unrecognized key: "([^"]*)"/;function formatSubmitValidationIssues(args2,issues){let joined=issues.map((issue3)=>{let pathLabel=issue3.path.length>0?issue3.path.join("."):"(root)",receivedSource,haveReceivedSource=!1;if(issue3.path.length>0)receivedSource=resolveReceivedValue(args2,issue3.path),haveReceivedSource=!0;else{let key2=UNRECOGNIZED_KEY_PATTERN.exec(issue3.message)?.[1];if(key2!==void 0&&args2!==null&&typeof args2==="object")receivedSource=args2[key2],haveReceivedSource=!0}let received=haveReceivedSource?` (${renderReceivedValue(receivedSource)})`:"";return`${pathLabel}: ${issue3.message}${received}`}).join("; ");if(joined.length<=MAX_FORMATTED_ISSUE_MESSAGE_CHARS)return joined;return`${joined.slice(0,MAX_FORMATTED_ISSUE_MESSAGE_CHARS)}… [truncated: ${issues.length} validation issue(s) exceed the ${MAX_FORMATTED_ISSUE_MESSAGE_CHARS}-char diagnostic budget; fix the first listed issue(s) and resubmit]`}var MAX_TRACKED_SUBMIT_SESSIONS=128,SUBMIT_REJECTION_HINT_THRESHOLD=3,consecutiveSubmitRejections=new Map;function submitRejectionKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}`+String.fromCharCode(0)+sessionID}function noteSubmitRejection(directory,sessionID){let key2=submitRejectionKey(directory,sessionID),next=(consecutiveSubmitRejections.get(key2)??0)+1;consecutiveSubmitRejections.set(key2,next);while(consecutiveSubmitRejections.size>MAX_TRACKED_SUBMIT_SESSIONS){let oldest=consecutiveSubmitRejections.keys().next().value;if(oldest===void 0)break;consecutiveSubmitRejections.delete(oldest)}return next}function clearSubmitRejections(directory,sessionID){consecutiveSubmitRejections.delete(submitRejectionKey(directory,sessionID))}async function executeSubmitPrReviewResult(args2,directory,context={}){let parsed=SubmitPrReviewResultArgsSchema.safeParse(args2),childSessionId=context.sessionID?.trim();if(!childSessionId)return JSON.stringify({success:!1,message:"submit_pr_review_result requires an authenticated child session"});if(!parsed.success){let count=noteSubmitRejection(directory,childSessionId),hint=count>=SUBMIT_REJECTION_HINT_THRESHOLD?` — ${count} consecutive rejections: re-read the tool schema; do NOT resubmit the same payload shape.`:"",message=`Invalid PR-review result: ${formatSubmitValidationIssues(args2,parsed.error.issues)}${hint}`;return await recordPrReviewSubmitRejection(directory,childSessionId,message),JSON.stringify({success:!1,message})}clearSubmitRejections(directory,childSessionId);let outcome=await submitPrReviewResult(directory,childSessionId,{...parsed.data.batchId?{batchId:parsed.data.batchId}:{},...parsed.data.laneId?{laneId:parsed.data.laneId}:{},revisionDigest:parsed.data.revisionDigest,result:parsed.data.result});return JSON.stringify({success:outcome.status==="recorded"||outcome.status==="duplicate",...outcome})}var submit_pr_review_result=createSwarmTool({description:"Submit exactly one typed CLEAN, FINDINGS, or INCOMPLETE result for the active child-bound PR-review base/micro lane. The authenticated child session identifies its exact delegation and supplies authoritative batch/lane provenance; optional batchId/laneId values are checked when present. The receipt is atomically bound to the child session, workflow instance, revision, batch, lane, root, base, and head. Identical replay is idempotent; conflicting or late submissions fail closed. Exception (issue #2585): when a lane's child is terminally unavailable (cancelled, stale, or liveness-error), the lane's dispatching parent session may submit one repair receipt for that lane; the receipt records the architect provenance and stays bound to the dead child session. Every other session is still refused. Call once, then stop.",args:{schemaVersion:SubmitPrReviewResultArgsSchema.shape.schemaVersion,batchId:SubmitPrReviewResultArgsSchema.shape.batchId,laneId:SubmitPrReviewResultArgsSchema.shape.laneId,revisionDigest:SubmitPrReviewResultArgsSchema.shape.revisionDigest,result:SubmitPrReviewResultArgsSchema.shape.result},execute:executeSubmitPrReviewResult});init_zod();init_path_security();init_create_tool();import*as fs218 from"node:fs";import*as path358 from"node:path";var BINARY_EXTENSIONS2=new Set([".png",".jpg",".jpeg",".gif",".bmp",".ico",".svg",".woff",".woff2",".ttf",".eot",".mp3",".mp4",".avi",".mov",".pdf",".zip",".tar",".gz",".rar"]),WINDOWS_RESERVED_NAMES6=/^(con|prn|aux|nul|com[1-9]|lpt[1-9])(\.|:|$)/i;function containsWindowsAttacks5(str){if(/^[A-Za-z]:[/\\]/.test(str))return!0;if(/:[^\\/]/.test(str))return!0;let parts=str.split(/[/\\]/);for(let part of parts)if(WINDOWS_RESERVED_NAMES6.test(part))return!0;return!1}function isPathInWorkspace4(filePath,workspace){try{let resolvedPath=path358.resolve(workspace,filePath);return isCanonicalPathWithinRoot(resolvedPath,workspace)}catch{return!1}}function validateFilePath2(filePath,workspace){if(!filePath||filePath.trim()==="")return!1;if(containsPathTraversal(filePath))return!1;if(containsControlChars(filePath))return!1;if(containsWindowsAttacks5(filePath))return!1;return isPathInWorkspace4(filePath,workspace)}function findContextMatch(content,contextBefore,contextAfter,oldContent){let lines=splitDiffLines(content);if((!contextBefore||contextBefore.length===0)&&(!contextAfter||contextAfter.length===0))return null;if(contextBefore&&contextBefore.length>0)for(let i=0;i<=lines.length-contextBefore.length;i++){let slice=lines.slice(i,i+contextBefore.length);if(arraysEqual2(slice,contextBefore)){let afterStart=i+contextBefore.length;if(contextAfter&&contextAfter.length>0){for(let j=afterStart;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))if(j===afterStart)return{startLineIndex:i,endLineIndex:j+contextAfter.length-1,matchedBefore:contextBefore,matchedAfter:contextAfter};else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent),betweenLines=lines.slice(afterStart,j);if(arraysEqual2(betweenLines,oldContentLines))return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}else return{startLineIndex:i,endLineIndex:j-1,matchedBefore:contextBefore,matchedAfter:contextAfter}}return null}else if(oldContent&&oldContent.length>0){let oldContentLines=splitDiffLines(oldContent);for(let k=afterStart;k<=lines.length-oldContentLines.length;k++){let candidate2=lines.slice(k,k+oldContentLines.length);if(arraysEqual2(candidate2,oldContentLines))return{startLineIndex:i,endLineIndex:k+oldContentLines.length-1,matchedBefore:contextBefore,matchedAfter:[]}}return null}else return{startLineIndex:i,endLineIndex:afterStart-1,matchedBefore:contextBefore,matchedAfter:[]}}}else if(contextAfter&&contextAfter.length>0)for(let j=0;j<=lines.length-contextAfter.length;j++){let afterSlice=lines.slice(j,j+contextAfter.length);if(arraysEqual2(afterSlice,contextAfter))return{startLineIndex:0,endLineIndex:j-1,matchedBefore:[],matchedAfter:contextAfter}}return null}function arraysEqual2(a,b){if(a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(a[i]!==b[i])return!1;return!0}function isBinaryFile4(filePath){let ext=path358.extname(filePath).toLowerCase();return BINARY_EXTENSIONS2.has(ext)}function splitDiffLines(content){if(content==="")return[];return content.endsWith(`
|
|
7783
7783
|
`)?content.slice(0,-1).split(`
|
|
7784
7784
|
`):content.split(`
|
|
7785
7785
|
`)}function generateFileHeader(file3){return`diff --git a/${file3} b/${file3}
|
|
@@ -7819,7 +7819,7 @@ ${scopeWarning}`:scopeWarning}}function recoverTaskStateFromDelegations(taskId,d
|
|
|
7819
7819
|
`).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 _internals302.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 _internals302={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()}init_timeout();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"}}var SEARCH_TIMEOUT_MS=6000;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,timeoutError2=new WebSearchError(`Tavily search timed out after ${SEARCH_TIMEOUT_MS}ms`);try{response=await withTimeoutSignal((signal2)=>fetch("https://api.tavily.com/search",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(requestBody),signal:signal2}),SEARCH_TIMEOUT_MS,timeoutError2)}catch(err2){if(err2===timeoutError2)throw 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,braveTimeoutError=new WebSearchError(`Brave search timed out after ${SEARCH_TIMEOUT_MS}ms`);try{response=await withTimeoutSignal((signal2)=>fetch(url3.toString(),{method:"GET",headers:{"X-Subscription-Token":this.apiKey,Accept:"application/json"},signal:signal2}),SEARCH_TIMEOUT_MS,braveTimeoutError)}catch(err2){if(err2===braveTimeoutError)throw 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 fail3={success:!1,reason:"invalid_args",message:parsed.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")};return JSON.stringify(fail3,null,2)}let dirResult=resolveWorkingDirectory(parsed.data.working_directory,directory);if(!dirResult.success){let fail3={success:!1,reason:"invalid_working_directory",message:dirResult.message};return JSON.stringify(fail3,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 fail3={success:!1,reason:err2 instanceof WebSearchConfigError?"missing_api_key":"provider_init_failed",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail3,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 fail3={success:!1,reason:err2 instanceof WebSearchError?"search_failed":"unknown",message:err2 instanceof Error?err2.message:String(err2)};return JSON.stringify(fail3,null,2)}}});async function captureSearchEvidence(directory,query,results){try{let written=await _internals303.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 _internals303={writeEvidenceDocuments};init_zod();init_loader();init_schema();init_curator_llm_factory();init_knowledge_curator();init_skill_generator();init_schema3();init_store5();init_create_tool();init_resolve_working_directory();import*as path366 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,path366.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 fs225 from"node:fs";import path367 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=_internals304.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=_internals304.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=path367.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=path367.dirname(validatedPath);try{await fs225.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path367.join(evidenceDir,`.${filename}.tmp`);return await fs225.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs225.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 _internals304={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2,lockProfileForIdentity},write_drift_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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();init_council_review_identity();import fs226 from"node:fs";import path368 from"node:path";init_types();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=COUNCIL_MEMBER_ROLES,VerdictSchema3=exports_external.object({agent:exports_external.string().min(1).max(64),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 resolveFinalCouncilVerdicts(verdicts){let resolved=[],distinctRoles=[],unknownAgents=[],duplicateAgents=[];for(let verdict of verdicts){let role=resolveCouncilMemberRole(verdict.agent);if(!role){if(!unknownAgents.includes(verdict.agent))unknownAgents.push(verdict.agent);continue}if(distinctRoles.includes(role)){if(!duplicateAgents.includes(verdict.agent))duplicateAgents.push(verdict.agent);continue}distinctRoles.push(role),resolved.push({...verdict,agent:role})}return{resolved,distinctRoles,unknownAgents,duplicateAgents}}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?computePlanLedgerHash(plan):void 0,planId=plan?derivePlanId(plan):void 0,planIdentityHash=plan?derivePlanIdentityHash(plan):void 0,reviewHash=plan?computeCouncilReviewHash(plan):null,identity=computeCouncilReviewIdentity({level:"final",scope:{kind:"final",final:!0},plan,config:config3.council}),completionPolicy=resolveFinalCompletionPolicy(config3.council),{resolved,distinctRoles,unknownAgents,duplicateAgents}=resolveFinalCouncilVerdicts(input.verdicts),membersVoted=distinctRoles,membersAbsent=FINAL_COUNCIL_MEMBERS.filter((member)=>!distinctRoles.includes(member)),requiredMembers=completionPolicy.mode==="quorum"?completionPolicy.minimumMembers:FINAL_COUNCIL_MEMBERS.length;return runCouncilAttempt({directory,scope:{kind:"final",identityDigest:identity.identityDigest},clientRound:input.roundNumber,maxRounds:config3.council?.maxRounds??3,sessionID:ctx?.sessionID,escalationConfigured:config3.council?.escalateOnMaxRounds!==void 0,request:input,verdictCount:input.verdicts.length,members:[...new Set(input.verdicts.map((v)=>v.agent))].slice(0,5),probePendingEvidence:async(attemptId,round)=>hasFinalEvidenceAttempt(directory,attemptId,round),evaluate:async(authoritativeRound)=>{if(membersVoted.length<requiredMembers)return{disposition:"insufficient_quorum",response:{success:!1,reason:"insufficient_quorum",message:`Final council quorum not met: ${membersVoted.length} of ${requiredMembers} required distinct canonical members provided verdicts (policy: ${completionPolicy.mode}${completionPolicy.mode==="quorum"?`, minimumMembers: ${completionPolicy.minimumMembers}`:""}). Members voted: [${membersVoted.join(", ")}]. Members absent: [${membersAbsent.join(", ")}].`+(unknownAgents.length>0?` Unknown identities (never counted): [${unknownAgents.join(", ")}].`:"")+(duplicateAgents.length>0?` Duplicate identities (collapsed): [${duplicateAgents.join(", ")}].`:"")+" Dispatch the absent council members with project-scoped context and collect their verdicts before calling write_final_council_evidence.",membersVoted,membersAbsent,quorumRequired:requiredMembers,completionPolicy,...unknownAgents.length>0?{unknownAgents}:{},...duplicateAgents.length>0?{duplicateAgents}:{}},transition:"stay",gateEffect:"none"};let synthesis=synthesizeFinalCouncilAdvisory(input.projectSummary.trim(),resolved,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,...councilIdentityEvidenceFields(identity),final_completion_policy:completionPolicy,freshness_max_age_hours:config3.council?.freshnessMaxAgeHours??24,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=_internals305.validateSwarmPath(directory,path368.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=path368.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,completionPolicy,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,path368.join("evidence","final-council.json"),"write-final-council-evidence",attemptId,async()=>{let currentPlan=await loadPlan(directory);if(!currentPlan||computeCouncilReviewHash(currentPlan)!==reviewHash)throw Error("final council plan changed before evidence publication");await fs226.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path368.join(evidenceDir,`.final-council.${attemptId}.tmp`);try{await fs226.promises.writeFile(tempPath,JSON.stringify({entries:[{...evidenceEntry,attemptId}]},null,2),"utf-8"),await fs226.promises.rename(tempPath,validatedPath),invalidateCachedArtifact(validatedPath)}finally{await fs226.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({allowWorkingDirectoryOverride:!0,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. Quorum follows council.finalCompletionPolicy: default requires all five canonical roles with zero absentees; an explicit quorum policy accepts a bounded minimum of distinct canonical members. Member names may be exact canonical roles or multi-swarm prefixed names (e.g. local_critic); unknown and duplicate identities never count.",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 (canonical or multi-swarm prefixed names).")},execute:async(args2,directory,ctx)=>executeWriteFinalCouncilEvidence(args2,directory,ctx)});function hasFinalEvidenceAttempt(directory,attemptId,round){try{let evidencePath=validateSwarmPath(directory,path368.join("evidence","final-council.json")),parsed=JSON.parse(fs226.readFileSync(evidencePath,"utf8"));return Boolean(parsed.entries?.some((entry)=>entry.type==="final-council"&&entry.attemptId===attemptId&&entry.roundNumber===round))}catch{return!1}}var _internals305={validateSwarmPath};init_zod();import fs227 from"node:fs";import path369 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=_internals306.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=path369.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=path369.dirname(validatedPath);try{await fs227.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path369.join(evidenceDir,`.${filename}.tmp`);return await fs227.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs227.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 _internals306={normalizeVerdict2,VERDICT_SET_2,isAcceptedVerdict2},write_hallucination_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,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 fs228 from"node:fs";import path370 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=_internals307.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=path370.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=path370.dirname(validatedPath);try{await fs228.promises.mkdir(evidenceDir,{recursive:!0});let tempPath=path370.join(evidenceDir,`.${filename}.tmp`);return await fs228.promises.writeFile(tempPath,JSON.stringify(evidenceContent,null,2),"utf-8"),await fs228.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 _internals307={normalizeVerdict4,VERDICT_SET_4,isAcceptedVerdict4},write_mutation_evidence=createSwarmTool({allowWorkingDirectoryOverride:!0,description:'Write mutation gate evidence for a completed phase. Accepts phase, verdict (PASS/WARN/FAIL/SKIP), killRate, adjustedKillRate, summary, and optional survivedMutants. Normalizes uppercase verdicts to lowercase (PASS→pass, WARN→warn, FAIL→fail, SKIP→skip) and writes entries[0].type="mutation-gate" to .swarm/evidence/{phase}/mutation-gate.json using atomic temp+rename write. Use this after mutation_test tool returns to persist the gate verdict.',args:{phase:exports_external.number().int().min(1).describe("The phase number for the mutation gate (e.g., 1, 2, 3)"),verdict:exports_external.enum(VERDICT_SET_4).describe("Verdict of the mutation gate: 'PASS', 'WARN', 'FAIL', or 'SKIP'"),killRate:exports_external.number().optional().describe("The raw kill rate (e.g., 0.85)"),adjustedKillRate:exports_external.number().optional().describe("The adjusted kill rate accounting for timeout survived mutants (e.g., 0.87)"),summary:exports_external.string().describe("Human-readable summary of the mutation gate result"),survivedMutants:exports_external.string().optional().describe("Optional JSON-serialized list of survived mutants")},execute:async(args2,directory)=>{let rawPhase=args2.phase!==void 0?Number(args2.phase):0;try{let typedArgs={phase:Number(args2.phase),verdict:String(args2.verdict),killRate:args2.killRate!==void 0?Number(args2.killRate):void 0,adjustedKillRate:args2.adjustedKillRate!==void 0?Number(args2.adjustedKillRate):void 0,summary:String(args2.summary??""),survivedMutants:args2.survivedMutants!==void 0?String(args2.survivedMutants):void 0};return await executeWriteMutationEvidence(typedArgs,directory)}catch(error93){return JSON.stringify({success:!1,phase:rawPhase,message:error93 instanceof Error?error93.message:"Unknown error"},null,2)}}});init_zod();init_pr_review_contract();init_pr_workflow_gate();init_utils2();init_finding_policy();init_create_tool();import{createHash as createHash114,randomUUID as randomUUID48}from"node:crypto";import*as fs229 from"node:fs";import*as path371 from"node:path";var PersistedFindingSchema=PrReviewFindingSchema.extend({boundary:exports_external.enum(["post_explorer","post_reviewer","post_critic"]),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),recorded_at:exports_external.string().datetime()}).passthrough(),PersistedHandoffSchema=PrReviewHandoffSchema.extend({schema_version:exports_external.literal(1),run_id:PrReviewRunIdSchema,pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime()}).strict();function failure3(message){return JSON.stringify({success:!1,message},null,2)}async function readFindings(filePath){try{return(await readBoundedUtf8File2(filePath,PR_REVIEW_FINDINGS_MAX_BYTES,"findings artifact")).split(/\r?\n/).filter(Boolean).map((line,index)=>{let decoded;try{decoded=JSON.parse(line)}catch(error93){throw Error(`line ${index+1} is not JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(decoded!==null&&typeof decoded==="object"){let record3=decoded;if(record3.risk_impact===void 0)record3.risk_impact="UNKNOWN";if(record3.risk_tags===void 0)record3.risk_tags=[]}let parsed=PersistedFindingSchema.safeParse(decoded);if(!parsed.success)throw Error(`line ${index+1} violates the persisted finding schema: ${formatPrReviewValidationIssues(parsed.error.issues,decoded).join("; ")}`);return parsed.data})}catch(error93){if(error93.code==="ENOENT")return[];throw error93}}async function readBoundedUtf8File2(filePath,maxBytes,label){let stat25=await fs229.promises.stat(filePath);if(!stat25.isFile()||stat25.size>maxBytes)throw Error(`${label} is not a bounded regular file (max ${maxBytes} bytes)`);let text=await fs229.promises.readFile(filePath,"utf8"),bytes=Buffer.byteLength(text,"utf8");if(bytes>maxBytes)throw Error(`${label} exceeds ${maxBytes} bytes after read (got ${bytes})`);return text}async function atomicWrite8(filePath,content){await fs229.promises.mkdir(path371.dirname(filePath),{recursive:!0});let tempPath=path371.join(path371.dirname(filePath),`.${path371.basename(filePath)}.${randomUUID48()}.tmp`);try{await fs229.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"}),await fs229.promises.rename(tempPath,filePath)}finally{await fs229.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function atomicCreate(filePath,content){await fs229.promises.mkdir(path371.dirname(filePath),{recursive:!0});let tempPath=path371.join(path371.dirname(filePath),`.${path371.basename(filePath)}.${randomUUID48()}.tmp`);try{await fs229.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs229.promises.link(tempPath,filePath),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs229.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}var _internals308={atomicWrite:atomicWrite8,atomicCreate,assertBoundary:assertPrReviewArtifactBoundary,assertCriticSettlements,readFindings};function operationFailure(operation,relativePath2,expected,error93){return failure3(`operation ${operation} path "${relativePath2}": expected ${expected}, got ${JSON.stringify(error93 instanceof Error?error93.message:String(error93))}`)}function latestFindings(records){let latest=new Map;for(let record3 of records)latest.set(record3.finding_id,record3);return latest}function canonicalFindingRecords(records){return JSON.stringify(records.map((record3)=>({finding_id:record3.finding_id,status:record3.status,file_line:record3.file_line,evidence:record3.evidence,next_action:record3.next_action,severity:record3.severity,category:record3.category,confidence:record3.confidence,provenance:record3.provenance,risk_impact:record3.risk_impact,risk_tags:record3.risk_tags,critic_status:record3.critic_status})).sort((left,right)=>left.finding_id.localeCompare(right.finding_id)))}function policyLocation(fileLine){let match=fileLine.trim().match(/^(.*?):(\d+)(?:-(\d+))?$/);if(!match)return{file:fileLine.trim(),line:1};return{file:match[1],line:Number(match[2]),...match[3]?{lineEnd:Number(match[3])}:{}}}function policyCandidates(records,sessionID,boundary){return records.map((record3)=>({finding:record3.evidence,severity:record3.severity??"NONE",action:record3.next_action,confidence:record3.confidence??"MEDIUM",category:record3.category??"review-finding",location:policyLocation(record3.file_line),provenance:((record3.provenance?.length)?record3.provenance:[`session:${sessionID}`]).map((identity)=>({identity,lane:boundary})),status:record3.status,sourceFindingId:record3.finding_id}))}function assertCriticSettlements(records,existing,authoritativeCriticVerdicts){let priorById=latestFindings(existing.filter((record3)=>record3.boundary==="post_reviewer")),settlements=[];for(let record3 of records){let prior=priorById.get(record3.finding_id),authoritative=authoritativeCriticVerdicts.get(record3.finding_id),needsCriticAuthority=prior?.next_action==="route_to_critic"||record3.critic_status!==void 0;if(needsCriticAuthority&&!authoritative)throw Error(`critic settlement for ${record3.finding_id} has no authenticated authoritative critic verdict`);if(authoritative?.status==="DOWNGRADED"&&record3.severity===void 0)throw Error(`critic settlement for ${record3.finding_id} DOWNGRADED verdict requires an explicit severity matching the authenticated authoritative critic verdict`);if(authoritative&&record3.severity!==void 0&&authoritative.severity!==record3.severity)throw Error(`critic settlement for ${record3.finding_id} severity contradicts the authenticated authoritative critic verdict`);if(record3.critic_status&&authoritative){if(record3.critic_status!==authoritative.status)throw Error(`critic settlement for ${record3.finding_id} status "${record3.critic_status}" contradicts the authenticated authoritative critic status "${authoritative.status}"`)}let outcome=authoritative?.status==="DISPROVED"||record3.status==="DISPROVED"?"DISPROVED":authoritative?.status==="DOWNGRADED"?"DOWNGRADED":authoritative?.status==="UPHELD"?"UPHELD":prior?.severity&&record3.severity&&prior.severity!==record3.severity?"DOWNGRADED":"UPHELD",settled=settleCriticFinding({finding:{id:record3.finding_id,status:record3.status,severity:record3.severity??"NONE",action:record3.next_action},outcome,finalSeverity:record3.severity,finalAction:record3.next_action});if(settled.finalFinding.severity!==(record3.severity??"NONE")||settled.finalFinding.action!==record3.next_action)throw Error(`critic settlement for ${record3.finding_id} does not match the final persisted severity/action`);if(needsCriticAuthority||authoritative)settlements.push({findingId:record3.finding_id,terminal:settled.terminal,status:settled.status,finalFinding:settled.finalFinding,handoffFindingIds:settled.handoffFindingIds})}return settlements}async function executeWritePrReviewArtifact(args2,directory,context={}){let parsed=WritePrReviewArtifactArgsSchema.safeParse(args2);if(!parsed.success)return failure3(`Invalid PR-review artifact: ${formatPrReviewValidationIssues(parsed.error.issues,args2).join("; ")}`);let sessionID=context.sessionID?.trim();if(!sessionID)return failure3(formatPrReviewRuntimeFieldError("session_id","a non-empty active session identifier",context.sessionID));let state2;try{state2=await readPrWorkflowGateState(directory,sessionID)}catch(error93){return operationFailure("read",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a bounded valid PR workflow state artifact",error93)}if(state2?.mode!=="PR_REVIEW"||!state2.prHeadSha)return failure3(formatPrReviewRuntimeFieldError("workflow.mode",'an active head-bound "PR_REVIEW" workflow',state2?{mode:state2.mode,pr_head_sha:state2.prHeadSha}:null));if(state2.prHeadSha!==parsed.data.pr_head_sha.toLowerCase())return failure3(formatPrReviewRuntimeFieldError("pr_head_sha",`"${state2.prHeadSha}"`,parsed.data.pr_head_sha));let resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){let message=error93 instanceof Error?error93.message:String(error93);return message.startsWith("BLOCKED: field ")?failure3(message):operationFailure("reserve",`pr-review/${parsed.data.run_id??"<generated-run-id>"}/run-reservation.json`,"a create-only reservation owned by the active workflow",error93)}let relativeFindingsPath=path371.join("pr-review",resolvedRunId,"findings.jsonl"),findingsPath;try{findingsPath=validateSwarmPath(directory,relativeFindingsPath)}catch(error93){return operationFailure("resolve",relativeFindingsPath.split(path371.sep).join("/"),"a contained path below the project .swarm directory",error93)}let existing;try{existing=await readFindings(findingsPath)}catch(error93){return failure3(`operation read path "${relativeFindingsPath.split(path371.sep).join("/")}": expected bounded JSONL matching the persisted findings schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsed.data.kind==="findings"){let findingsInput=parsed.data,findingIds=findingsInput.records.map((record3)=>record3.finding_id),existingBoundaryRecords=existing.filter((record3)=>record3.boundary===findingsInput.boundary),hasExistingBoundaryRecords=existingBoundaryRecords.length>0,isExactReplay=hasExistingBoundaryRecords&&canonicalFindingRecords(existingBoundaryRecords)===canonicalFindingRecords(findingsInput.records),boundaryCommitted=state2.prReviewArtifactRunId===resolvedRunId&&(state2.prReviewArtifactBoundaries??[]).includes(findingsInput.boundary),existingBoundaryIds=new Set(existingBoundaryRecords.map((record3)=>record3.finding_id)),requestedFindingIds=new Set(findingIds),isPostExplorerSupersession=boundaryCommitted&&findingsInput.boundary==="post_explorer"&&Boolean(state2.prReviewTriggerEvalPath)&&existingBoundaryIds.size<requestedFindingIds.size&&[...existingBoundaryIds].every((id)=>requestedFindingIds.has(id)),isCommittedReplay=isExactReplay&&boundaryCommitted,partialAdmissionToRollback,rollbackPartialAdmission=async()=>{if(!partialAdmissionToRollback)return;try{return await rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,partialAdmissionToRollback)?void 0:"partial base coverage admission could not be safely rolled back because durable state changed"}catch(error93){return`partial base coverage admission rollback failed: ${error93 instanceof Error?error93.message:String(error93)}`}},withPartialAdmissionRollback=async(result)=>{let rollbackError=await rollbackPartialAdmission();if(!rollbackError)return result;try{let decoded=JSON.parse(result);return typeof decoded.message==="string"?failure3(`${decoded.message}; ${rollbackError}`):result}catch{return result}};if(!isCommittedReplay)try{await _internals308.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,findingsInput.partial_base_coverage?{skipBaseCoverage:!0}:void 0)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}try{await assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,findingsInput.boundary,findingsInput.records)}catch(error93){return failure3(formatPrReviewRuntimeFieldError("records",`records exactly matching authoritative ${findingsInput.boundary} verdicts and disposition rules`,error93 instanceof Error?error93.message:String(error93)))}if(hasExistingBoundaryRecords&&boundaryCommitted&&!isExactReplay&&!isPostExplorerSupersession)return failure3(formatPrReviewRuntimeFieldError("records",`an exact replay of the already-persisted "${findingsInput.boundary}" boundary`,findingsInput.records));if(!isCommittedReplay)try{if(findingsInput.partial_base_coverage){let hadPartialAdmission=Boolean(state2.prReviewPartialBaseCoverage||state2.prReviewCoverageDisclosurePath||state2.prReviewCoverageDisclosureDigest);if(await _internals308.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds,{skipBaseCoverage:!0}),state2=await admitPrReviewPartialBaseCoverage2(directory,sessionID,resolvedRunId,findingsInput.partial_base_coverage.unresolved_dimensions),!hadPartialAdmission&&state2.prReviewPartialBaseCoverage&&state2.prReviewCoverageDisclosurePath&&state2.prReviewCoverageDisclosureDigest)partialAdmissionToRollback={runId:state2.prReviewPartialBaseCoverage.runId,boundary:findingsInput.boundary,relativePath:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}if(findingsInput.partial_base_coverage)await _internals308.assertBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,findingIds)}catch(error93){return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError(findingsInput.partial_base_coverage?"partial_base_coverage":"boundary",findingsInput.partial_base_coverage?"a terminal N-of-6 settlement: every declared unresolved dimension terminal (typed failure, explicit cancellation, or never launched) after every other boundary predicate passes":`the legal next "${findingsInput.boundary}" checkpoint for run "${resolvedRunId}" with exact inventory [${findingIds.join(", ")}]`,error93 instanceof Error?error93.message:String(error93))))}let recordedAt=new Date().toISOString(),appended=isExactReplay?[]:findingsInput.records.map((record3)=>({...record3,boundary:findingsInput.boundary,pr_head_sha:state2.prHeadSha,recorded_at:recordedAt})),allRecords=[...existing,...appended],serializedFindings=allRecords.map((record3)=>JSON.stringify(record3)).join(`
|
|
7820
7820
|
`)+(allRecords.length>0?`
|
|
7821
7821
|
`:""),findingsDigest=createHash114("sha256").update(serializedFindings,"utf8").digest("hex"),criticSettlements;if(findingsInput.boundary==="post_critic")try{let authoritativeCriticVerdicts=existing.some((record3)=>record3.boundary==="post_reviewer"&&record3.next_action==="route_to_critic")?await readAuthoritativePrReviewCriticVerdicts(directory,sessionID):new Map;criticSettlements=assertCriticSettlements(findingsInput.records,existing,authoritativeCriticVerdicts)}catch(error93){return withPartialAdmissionRollback(operationFailure("validate",relativeFindingsPath.split(path371.sep).join("/"),"an authoritative critic settlement matching the authenticated critic verdict map",error93))}if(!isExactReplay){let serializedBytes=Buffer.byteLength(serializedFindings,"utf8");if(serializedBytes>PR_REVIEW_FINDINGS_MAX_BYTES)return withPartialAdmissionRollback(failure3(formatPrReviewRuntimeFieldError("records",`a complete findings artifact at most ${PR_REVIEW_FINDINGS_MAX_BYTES} UTF-8 bytes`,`${serializedBytes} bytes`)));try{await _internals308.atomicWrite(findingsPath,serializedFindings)}catch(error93){return withPartialAdmissionRollback(operationFailure("write",relativeFindingsPath.split(path371.sep).join("/"),"an atomic findings checkpoint write",error93))}}let latest2=latestFindings(allRecords);if(findingsInput.boundary==="post_critic")try{let synthesis=synthesizePrReviewFindings({candidates:policyCandidates([...latest2.values()],sessionID,findingsInput.boundary)});await persistReviewOutcome({projectRoot:directory,routeReceipt:{kind:"pr_review_finding_policy",version:1,sessionId:sessionID,taskId:resolvedRunId,boundary:findingsInput.boundary,prHeadSha:state2.prHeadSha,findingsPath:relativeFindingsPath.split(path371.sep).join("/"),findingsDigest},synthesis:{...synthesis,criticSettlements}})}catch(error93){return withPartialAdmissionRollback(operationFailure("persist",`pr-review/${resolvedRunId}/finding-policy.json`,"an authoritative version-1 critic settlement and finding-policy evidence record",error93))}let handoffRequired=deriveFeedbackHandoffFindingIds([...latest2.values()]).length>0;if(!isCommittedReplay)try{await markPrReviewArtifactBoundary(directory,sessionID,resolvedRunId,findingsInput.boundary,relativeFindingsPath.split(path371.sep).join("/"),findingIds,handoffRequired)}catch(error93){return withPartialAdmissionRollback(operationFailure("update",`pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,`a durable ${findingsInput.boundary} boundary receipt`,error93))}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeFindingsPath.split(path371.sep).join("/"),boundary:findingsInput.boundary,appended:appended.length,replayed:isExactReplay,handoff_required:handoffRequired,...state2.prReviewPartialBaseCoverage?{partial_base_coverage:{unresolved_dimensions:normalizePrReviewPartialBaseCoverageRecord(state2.prReviewPartialBaseCoverage).unresolvedDimensions.map((entry)=>({dimension:entry.dimension,terminal_state:entry.terminalState,reason_kind:entry.reasonKind,failure_class:entry.failureClass})),path:state2.prReviewCoverageDisclosurePath,digest:state2.prReviewCoverageDisclosureDigest}}:{}},null,2)}let latest=latestFindings(existing),actionableIds=deriveFeedbackHandoffFindingIds([...latest.values()]),requestedIds=[...new Set(parsed.data.handoff.finding_ids)].sort();if(actionableIds.length===0||JSON.stringify(actionableIds)!==JSON.stringify(requestedIds))return failure3(`field handoff.finding_ids: expected authoritative actionable set [${actionableIds.join(", ")||"(none)"}], got requested [${requestedIds.join(", ")||"(none)"}]`);let relativeHandoffPath=path371.join("pr-review",resolvedRunId,"feedback-handoff.json"),handoffPath;try{handoffPath=validateSwarmPath(directory,relativeHandoffPath)}catch(error93){return operationFailure("resolve",relativeHandoffPath.split(path371.sep).join("/"),"a contained path below the project .swarm directory",error93)}let handoffRecord={schema_version:1,run_id:resolvedRunId,pr_head_sha:state2.prHeadSha,created_at:new Date().toISOString(),...parsed.data.handoff},comparableHandoff=(record3)=>({schema_version:record3.schema_version,run_id:record3.run_id,pr_head_sha:record3.pr_head_sha,pr_url:record3.pr_url,finding_ids:record3.finding_ids,summary:record3.summary,provenance:record3.provenance}),handoffsMatch=(existing2)=>JSON.stringify(comparableHandoff(existing2))===JSON.stringify(comparableHandoff(handoffRecord)),readPersistedHandoff=async()=>{let raw=await readBoundedUtf8File2(handoffPath,PR_REVIEW_HANDOFF_MAX_BYTES,"handoff artifact"),decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`invalid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}let validated=PersistedHandoffSchema.safeParse(decoded);if(!validated.success)throw Error(`schema mismatch: ${formatPrReviewValidationIssues(validated.error.issues,decoded).join("; ")}`);return validated.data},existingHandoff=null;try{existingHandoff=await readPersistedHandoff()}catch(error93){if(error93.code!=="ENOENT")return failure3(`operation read path "${relativeHandoffPath.split(path371.sep).join("/")}": expected bounded JSON matching the persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(existingHandoff){if(!handoffsMatch(existingHandoff))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting handoff content")}else{let serializedHandoff=`${JSON.stringify(handoffRecord,null,2)}
|
|
7822
|
-
`,serializedHandoffBytes=Buffer.byteLength(serializedHandoff,"utf8");if(serializedHandoffBytes>PR_REVIEW_HANDOFF_MAX_BYTES)return failure3(formatPrReviewRuntimeFieldError("handoff",`a persisted handoff artifact at most ${PR_REVIEW_HANDOFF_MAX_BYTES} UTF-8 bytes`,`${serializedHandoffBytes} bytes`));let created;try{created=await _internals308.atomicCreate(handoffPath,serializedHandoff)}catch(error93){return operationFailure("create",relativeHandoffPath.split(path371.sep).join("/"),"an atomic create-only handoff artifact",error93)}if(!created){let raced;try{raced=await readPersistedHandoff()}catch(error93){return failure3(`operation read path "${relativeHandoffPath.split(path371.sep).join("/")}": expected the concurrently persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(!handoffsMatch(raced))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting concurrent handoff content")}}let alreadyOffered;try{alreadyOffered=(await markPrReviewHandoffComplete(directory,sessionID,resolvedRunId,relativeHandoffPath.split(path371.sep).join("/"))).alreadyOffered}catch(error93){return operationFailure("update",`pr-review/${resolvedRunId}/feedback-consent.json and pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a matching durable consent offer and handoff receipt",error93)}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeHandoffPath.split(path371.sep).join("/"),finding_count:actionableIds.length,already_offered:alreadyOffered,confirmation_command:`/swarm pr-feedback ${parsed.data.handoff.pr_url} continue from .swarm/${relativeHandoffPath.split(path371.sep).join("/")}`},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,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:PrReviewRunIdSchema.optional(),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(PrReviewFindingSchema).min(1).max(1000).optional(),partial_base_coverage:PrReviewPartialBaseCoverageSchema.optional(),handoff:PrReviewHandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID49}from"node:crypto";import fs230 from"node:fs";import path372 from"node:path";var _internals309={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync,markPrReviewTriggerEvaluationComplete};function comparableTriggerReceipt(receipt){return JSON.stringify({...receipt,evaluated_at:void 0,base_verification:void 0})}async function readBoundedTriggerReceipt(destination){let stat25=await fs230.promises.stat(destination);if(!stat25.isFile()||stat25.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt is not a bounded regular file (max ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes)`);let raw=await fs230.promises.readFile(destination,"utf8"),bytes=Buffer.byteLength(raw,"utf8");if(bytes>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt exceeds ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes after read (got ${bytes})`);let decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`trigger evaluation receipt is not valid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsePrReviewTriggerReceipt(decoded),decoded.schema_version!==2)throw Error("trigger evaluation receipt must use schema_version 2");return decoded}async function createTriggerReceipt(destination,content){let parent=path372.dirname(destination),tempPath=path372.join(parent,`.trigger-eval.${randomUUID49()}.tmp`);await fs230.promises.mkdir(parent,{recursive:!0});try{await fs230.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs230.promises.link(tempPath,destination),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs230.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals309.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals309.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals309.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest5=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest5)return digest5}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals309.resolveMergeBase!==resolveExactMergeBase)return _internals309.resolveMergeBase(directory,baseRef,prHeadSha);return _internals309.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:PrReviewRunIdSchema.optional(),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: ${formatPrReviewValidationIssues(parsed.error.issues,args2).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(formatPrReviewRuntimeFieldError("pr_head_sha",`"${gateState.prHeadSha}"`,parsed.data.pr_head_sha));try{await assertPrReviewBaseCoverageSettled2(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 resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let batchRead=findByBatchIdDetailed(directory,row.source_batch_id,{parentSessionId:sessionID});if(batchRead.status==="uncertain")return failure4(`MATCHED trigger ${row.trigger_id} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Nothing was persisted, so this call is retryable as-is once the store is readable.`);let record3=batchRead.value.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,provenanceFailure=!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,livenessTerminalDead=provenanceFailure&&!!record3&&record3.mode==="swarm-pr-review:micro"&&recordOwnedLanes.includes(row.trigger_id)&&(record3.status==="stale"||record3.status==="error")&&record3.result?.workflowLaneFailureClass==="liveness"&&!record3.result?.outputRef?.trim()&&!outputArtifact&&record3.workspace?.prHeadSha===parsed.data.pr_head_sha&&record3.workspace?.gitHead===parsed.data.pr_head_sha;if(provenanceFailure&&!livenessTerminalDead)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);if(livenessTerminalDead){coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason:`liveness-terminal dead family: lane settled ${record3.status} with typed liveness class (presumed host abandonment), no retained artifact; family disclosed unattested`});continue}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");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){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}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);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 resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let artifact=buildPrReviewTriggerReceiptV2({run_id:resolvedRunId,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,base_verification:baseVerification}),relativePath2=path372.join("pr-review",resolvedRunId,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let replayed=!1;try{let existing=null;try{existing=await readBoundedTriggerReceipt(destination)}catch(error93){if(error93.code!=="ENOENT")throw error93}if(existing){if(comparableTriggerReceipt(existing)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${resolvedRunId}" with conflicting content`);artifact=existing,replayed=!0}else if(!await createTriggerReceipt(destination,`${JSON.stringify(artifact,null,2)}
|
|
7822
|
+
`,serializedHandoffBytes=Buffer.byteLength(serializedHandoff,"utf8");if(serializedHandoffBytes>PR_REVIEW_HANDOFF_MAX_BYTES)return failure3(formatPrReviewRuntimeFieldError("handoff",`a persisted handoff artifact at most ${PR_REVIEW_HANDOFF_MAX_BYTES} UTF-8 bytes`,`${serializedHandoffBytes} bytes`));let created;try{created=await _internals308.atomicCreate(handoffPath,serializedHandoff)}catch(error93){return operationFailure("create",relativeHandoffPath.split(path371.sep).join("/"),"an atomic create-only handoff artifact",error93)}if(!created){let raced;try{raced=await readPersistedHandoff()}catch(error93){return failure3(`operation read path "${relativeHandoffPath.split(path371.sep).join("/")}": expected the concurrently persisted handoff schema, got ${error93 instanceof Error?error93.message:String(error93)}`)}if(!handoffsMatch(raced))return failure3("field handoff: expected an exact retry of the persisted handoff, got conflicting concurrent handoff content")}}let alreadyOffered;try{alreadyOffered=(await markPrReviewHandoffComplete(directory,sessionID,resolvedRunId,relativeHandoffPath.split(path371.sep).join("/"))).alreadyOffered}catch(error93){return operationFailure("update",`pr-review/${resolvedRunId}/feedback-consent.json and pr-workflow-gates/${prWorkflowSessionFileStem(sessionID)}.json`,"a matching durable consent offer and handoff receipt",error93)}return JSON.stringify({success:!0,run_id:resolvedRunId,path:relativeHandoffPath.split(path371.sep).join("/"),finding_count:actionableIds.length,already_offered:alreadyOffered,confirmation_command:`/swarm pr-feedback ${parsed.data.handoff.pr_url} continue from .swarm/${relativeHandoffPath.split(path371.sep).join("/")}`},null,2)}var write_pr_review_artifact=createSwarmTool({allowWorkingDirectoryOverride:!0,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:PrReviewRunIdSchema.optional(),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(PrReviewFindingSchema).min(1).max(1000).optional(),partial_base_coverage:PrReviewPartialBaseCoverageSchema.optional(),handoff:PrReviewHandoffSchema.optional()},execute:executeWritePrReviewArtifact});init_zod();init_lane_output_store();init_pending_delegations();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_pr_workflow_gate();init_utils2();init_logger();init_create_tool();init_pr_review_trigger_contract();import{randomUUID as randomUUID49}from"node:crypto";import fs230 from"node:fs";import path372 from"node:path";var _internals309={resolvePrWorkflowRevisionDigest,resolvePrWorkflowRevisionDigestAsync,resolveMergeBase:resolveExactMergeBase,resolveMergeBaseAsync:resolveExactMergeBaseAsync,markPrReviewTriggerEvaluationComplete};function comparableTriggerReceipt(receipt){return JSON.stringify({...receipt,evaluated_at:void 0,base_verification:void 0})}async function readBoundedTriggerReceipt(destination){let stat25=await fs230.promises.stat(destination);if(!stat25.isFile()||stat25.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt is not a bounded regular file (max ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes)`);let raw=await fs230.promises.readFile(destination,"utf8"),bytes=Buffer.byteLength(raw,"utf8");if(bytes>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error(`trigger evaluation receipt exceeds ${PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES} bytes after read (got ${bytes})`);let decoded;try{decoded=JSON.parse(raw)}catch(error93){throw Error(`trigger evaluation receipt is not valid JSON: ${error93 instanceof Error?error93.message:String(error93)}`)}if(parsePrReviewTriggerReceipt(decoded),decoded.schema_version!==2)throw Error("trigger evaluation receipt must use schema_version 2");return decoded}async function createTriggerReceipt(destination,content){let parent=path372.dirname(destination),tempPath=path372.join(parent,`.trigger-eval.${randomUUID49()}.tmp`);await fs230.promises.mkdir(parent,{recursive:!0});try{await fs230.promises.writeFile(tempPath,content,{encoding:"utf8",flag:"wx"});try{return await fs230.promises.link(tempPath,destination),!0}catch(error93){if(error93.code==="EEXIST")return!1;throw error93}}finally{await fs230.promises.rm(tempPath,{force:!0}).catch(()=>{return})}}async function resolveCurrentRevisionDigest(directory,prHeadSha){if(_internals309.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest)return _internals309.resolvePrWorkflowRevisionDigest(directory,prHeadSha);return _internals309.resolvePrWorkflowRevisionDigestAsync(directory,prHeadSha)}var REVISION_DIGEST_RESOLUTION_ATTEMPTS=2;async function resolveCurrentRevisionDigestWithRetry(directory,prHeadSha){for(let attempt=1;attempt<=REVISION_DIGEST_RESOLUTION_ATTEMPTS;attempt+=1){let digest5=await resolveCurrentRevisionDigest(directory,prHeadSha);if(digest5)return digest5}return null}async function resolveReviewMergeBase(directory,baseRef,prHeadSha){if(_internals309.resolveMergeBase!==resolveExactMergeBase)return _internals309.resolveMergeBase(directory,baseRef,prHeadSha);return _internals309.resolveMergeBaseAsync(directory,baseRef,prHeadSha)}var WritePrReviewTriggerEvalArgsSchema=exports_external.object({run_id:PrReviewRunIdSchema.optional(),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: ${formatPrReviewValidationIssues(parsed.error.issues,args2).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(formatPrReviewRuntimeFieldError("pr_head_sha",`"${gateState.prHeadSha}"`,parsed.data.pr_head_sha));try{await assertPrReviewBaseCoverageSettled2(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 — dispatch the first swarm-pr-review:micro batch with the complete trigger_evaluation parameter on dispatch_lanes_async; that dispatch freezes the ledger this tool then persists");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 resolveCurrentRevisionDigestWithRetry(directory,parsed.data.pr_head_sha);if(!currentRevisionDigest)return failure4(`Active PR_REVIEW trigger evaluation could not bind the current exact revision digest for pr_head_sha "${parsed.data.pr_head_sha}" after ${REVISION_DIGEST_RESOLUTION_ATTEMPTS} attempts. A null digest collapses several causes: the bounded git call timed out, the git process failed to spawn, the working tree could not be read, or pr_head_sha was rejected as an unsafe revision token. This fails closed on purpose and has no bound-value fallback — no independently-bound durable PR_REVIEW revision digest exists to compare against, so accepting an unresolved digest would let a lane artifact self-certify its own revision. Nothing was persisted, so this call is retryable as-is. Recovery: confirm the checkout is readable and pr_head_sha exists here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);let citedLaneOwnership=new Map,coverageDegradations=[];for(let row of validatedRows){if(row.result!=="MATCHED")continue;let batchRead=findByBatchIdDetailed(directory,row.source_batch_id,{parentSessionId:sessionID});if(batchRead.status==="uncertain")return failure4(`MATCHED trigger ${row.trigger_id} cannot be validated: the delegation store is unreadable after ${batchRead.attempts} attempts (${batchRead.reason}); the batch's records are UNKNOWN, not absent. Nothing was persisted, so this call is retryable as-is once the store is readable.`);let record3=batchRead.value.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,provenanceFailure=!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,livenessTerminalDead=provenanceFailure&&!!record3&&record3.mode==="swarm-pr-review:micro"&&recordOwnedLanes.includes(row.trigger_id)&&(record3.status==="stale"||record3.status==="error")&&record3.result?.workflowLaneFailureClass==="liveness"&&!record3.result?.outputRef?.trim()&&!outputArtifact&&record3.workspace?.prHeadSha===parsed.data.pr_head_sha&&record3.workspace?.gitHead===parsed.data.pr_head_sha;if(provenanceFailure&&!livenessTerminalDead)return failure4(`MATCHED trigger ${row.trigger_id} does not reference a verifiable micro-lane provenance chain`);if(livenessTerminalDead){coverageDegradations.push({trigger_id:row.trigger_id,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id,reason:`liveness-terminal dead family: lane settled ${record3.status} with typed liveness class (presumed host abandonment), no retained artifact; family disclosed unattested`});continue}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");if(!gateState.prReviewBaseRef||!gateState.prReviewBaseSha)return failure4('Active PR_REVIEW trigger evaluation requires a durably bound review base; the active PR_REVIEW gate has no bound base_ref/base_sha, so the received scope cannot be verified against anything. Re-bind the review scope by dispatching the review lanes for this PR, or restart with abort_pr_workflow (kind "recovery").');let resolvedMergeBase=await resolveReviewMergeBase(directory,parsed.data.base_ref,parsed.data.pr_head_sha),baseVerification="live";if(resolvedMergeBase){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}`)}else if(parsed.data.base_ref===gateState.prReviewBaseRef&&parsed.data.base_sha.toLowerCase()===gateState.prReviewBaseSha)baseVerification="bound_fallback",criticalWarn(`PR_REVIEW trigger evaluation could not re-derive the merge base for base_ref "${parsed.data.base_ref}" at pr_head_sha "${parsed.data.pr_head_sha}"; proceeding on the durably bound, bind-time-verified review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}). The receipt discloses base_verification: bound_fallback and the final review report must disclose it too.`);else return failure4(`Active PR_REVIEW trigger evaluation could not resolve the exact merge base from base_ref "${parsed.data.base_ref}" and pr_head_sha "${parsed.data.pr_head_sha}", and the received scope does not equal the durably bound review scope (${gateState.prReviewBaseRef} at ${gateState.prReviewBaseSha}), so the bound-scope fallback does not apply. A null resolution collapses several causes: the bounded git call timed out, the git process failed to spawn, base_ref is not resolvable in this checkout, or base_ref/pr_head_sha was rejected as an unsafe revision token. Recovery: verify both revisions exist here (git rev-parse), retry once the environment settles, or restart with abort_pr_workflow (kind "recovery").`);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 resolvedRunId;try{resolvedRunId=await resolvePrReviewWriterRunId(directory,sessionID,parsed.data.run_id)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let artifact=buildPrReviewTriggerReceiptV2({run_id:resolvedRunId,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,base_verification:baseVerification}),relativePath2=path372.join("pr-review",resolvedRunId,"trigger-eval.json"),destination;try{destination=validateSwarmPath(directory,relativePath2)}catch(error93){return failure4(error93 instanceof Error?error93.message:String(error93))}let replayed=!1;try{let existing=null;try{existing=await readBoundedTriggerReceipt(destination)}catch(error93){if(error93.code!=="ENOENT")throw error93}if(existing){if(comparableTriggerReceipt(existing)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt already exists for run "${resolvedRunId}" with conflicting content`);artifact=existing,replayed=!0}else if(!await createTriggerReceipt(destination,`${JSON.stringify(artifact,null,2)}
|
|
7823
7823
|
`)){let raced=await readBoundedTriggerReceipt(destination);if(comparableTriggerReceipt(raced)!==comparableTriggerReceipt(artifact))return failure4(`PR_REVIEW trigger evaluation receipt concurrently appeared for run "${resolvedRunId}" with conflicting content`);artifact=raced,replayed=!0}}catch(error93){return failure4(`Failed to read or persist trigger evaluation at "${relativePath2.split(path372.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}try{await _internals309.markPrReviewTriggerEvaluationComplete(directory,sessionID,resolvedRunId,relativePath2.split(path372.sep).join("/"))}catch(error93){return failure4(`Failed to persist trigger evaluation gate receipt for "${relativePath2.split(path372.sep).join("/")}": ${error93 instanceof Error?error93.message:String(error93)}`)}return JSON.stringify({success:!0,replayed,run_id:resolvedRunId,path:relativePath2.split(path372.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,base_verification:baseVerification,...baseVerification==="bound_fallback"?{base_verification_note:"live merge-base re-derivation was unavailable; the bound review scope was used and MUST be disclosed in the final review report"}:{},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({allowWorkingDirectoryOverride:!0,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,authorize_pr_review_reentry:()=>authorize_pr_review_reentry,submit_pr_review_result:()=>submit_pr_review_result,approve_plan_critic:()=>approve_plan_critic,approve_retry_sounding_board:()=>approve_retry_sounding_board,recover_rework_task:()=>recover_rework_task,recover_stage_a_task:()=>recover_stage_a_task,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,record_branch_freshness:()=>record_branch_freshness,record_trace_validation:()=>record_trace_validation,record_merge_approval:()=>record_merge_approval,invalidate_pr_feedback_publication:()=>invalidate_pr_feedback_publication,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,run_phase_review:()=>run_phase_review,repair_gate_evidence:()=>repair_gate_evidence,repair_knowledge_receipt_ledger:()=>repair_knowledge_receipt_ledger,record_directive_override:()=>record_directive_override,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,scope_validate:()=>scope_validate,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_receipt_status:()=>knowledge_receipt_status,knowledge_archive:()=>knowledge_archive,swarm_memory_recall:()=>swarm_memory_recall,swarm_memory_propose:()=>swarm_memory_propose,swarm_memory_outcome:()=>swarm_memory_outcome,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_critic:()=>lean_turbo_critic,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()}tools.swarm_command=createSwarmCommandTool(agents,evaluationModelDispatcher,reviewModelDispatcher,config3?.auto_review,reviewAgentModelRegistry,getActiveAgentName),tools.phase_complete=createPhaseCompleteTool({reviewModelDispatcher,generatedAgentNames:reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName}),tools.run_phase_review=createRunPhaseReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_review=createLeanTurboReviewTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_critic=createLeanTurboCriticTool(reviewModelDispatcher,reviewAgentNames,reviewAgentModelRegistry,getActiveAgentName),tools.lean_turbo_run_phase=createLeanTurboRunPhaseTool(reviewAgentNames);let tracked={};for(let[name,def]of Object.entries(tools)){let execute2=def.execute;if(typeof execute2==="function")tracked[name]={...def,execute:withStartupFirstToolTracking(name,execute2)};else tracked[name]=def}return tracked}init_package();init_consent();init_vault();var PLUGIN_VERSION=package_default.version,MAX_DEDUP_PER_SESSION=4096,MAX_TRACKED_DEDUP_SESSIONS=500,GUIDANCE_CARRIER_ID_PREFIX2="swarm-guidance:",DIRECTIVE_TEXT_PREFIX="<swarm_system_directive";function safeStringify(value){try{return JSON.stringify(value)??""}catch{return String(value)}}var _internals310={appendRecord:appendTrainingVaultRecord,readConsent:(directory)=>readActiveTrainingConsent(directory),buildRecord:buildTrainingVaultRecord};function kindForRole(role){if(role==="user")return"user_message";if(role==="assistant")return"assistant_message";return null}function createTrainingCaptureObserver(directory){let dedupBySession=new Map;function markSeen(sessionId,recordId){let entry=dedupBySession.get(sessionId);if(!entry){entry={order:[],seen:new Set},dedupBySession.set(sessionId,entry);while(dedupBySession.size>MAX_TRACKED_DEDUP_SESSIONS){let oldest=dedupBySession.keys().next().value;if(oldest===void 0)break;dedupBySession.delete(oldest)}}if(entry.seen.has(recordId))return!1;if(entry.seen.add(recordId),entry.order.push(recordId),entry.order.length>MAX_DEDUP_PER_SESSION){let evicted=entry.order.shift();if(evicted!==void 0)entry.seen.delete(evicted)}return!0}function capture(kind,role,content,sessionId,source){let consent=_internals310.readConsent(directory);if(!consent)return;let record3=_internals310.buildRecord({directory,kind,role,content,sessionId,pluginVersion:PLUGIN_VERSION,source,consent});if(!markSeen(sessionId,record3.record_id))return;_internals310.appendRecord(directory,record3)}return{async observeMessages(output){try{let messages=output?.messages;if(!Array.isArray(messages))return;for(let message of messages)try{let info=message?.info;if(!info)continue;let sessionId=info.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)continue;if(typeof info.id==="string"&&info.id.startsWith(GUIDANCE_CARRIER_ID_PREFIX2))continue;let kind=kindForRole(info.role??"");if(!kind)continue;let parts=message.parts;if(!Array.isArray(parts))continue;for(let part of parts)try{if(part?.type!=="text")continue;let text=typeof part.text==="string"?part.text:"";if(text.length===0)continue;if(text.startsWith(DIRECTIVE_TEXT_PREFIX))continue;capture(kind,info.role??"",text,sessionId,"chat")}catch{}}catch{}}catch{}},async observeToolExecution(event){try{let sessionId=event?.sessionID;if(typeof sessionId!=="string"||sessionId.length===0)return;let tool3=typeof event?.tool==="string"?event.tool:"unknown",inputSummary=safeStringify(event?.input);if(inputSummary.length>0)capture("tool_call","tool",inputSummary,sessionId,"tool");let outputSummary=safeStringify(event?.error??event?.output??"");if(outputSummary.length>0&&outputSummary!=='""')capture("tool_result","tool",`${tool3}
|
|
7824
7824
|
${outputSummary}`,sessionId,"tool")}catch{}}}}init_utils();init_git_executable();init_project_boundary();init_timeout();function truncateToolOutput(output,maxLines,toolName,tailLines=10){if(!output)return output;if(tailLines>=maxLines)tailLines=Math.floor(maxLines/2);let lines=output.split(`
|
|
7825
7825
|
`);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(`
|