opencode-swarm 7.184.2 → 7.184.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/.opencode/skills/swarm-pr-review/SKILL.md +1 -1
  2. package/.opencode/skills/swarm-pr-review/references/lane-output-recoverability.md +11 -0
  3. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  4. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  5. package/dist/background/stage-b-gates.d.ts +1 -1
  6. package/dist/background/workspace-snapshot.d.ts +9 -0
  7. package/dist/cli/{coder-settlement-vqh4b7fb.js → coder-settlement-633ec0fb.js} +4 -4
  8. package/dist/cli/{config-doctor-8fp6s15v.js → config-doctor-bczcm4sg.js} +2 -2
  9. package/dist/cli/{core-75bsfgse.js → core-f4tzsgxp.js} +1 -1
  10. package/dist/cli/{curator-gwqs85sp.js → curator-9mzgd9dd.js} +23 -23
  11. package/dist/cli/{curator-drift-pmcpywr0.js → curator-drift-1x67b2vg.js} +5 -5
  12. package/dist/cli/{curator-llm-factory-g6hb1vvw.js → curator-llm-factory-vs1hgm6e.js} +23 -23
  13. package/dist/cli/{evidence-summary-service-rm0tp8d1.js → evidence-summary-service-fj2qa9eh.js} +8 -8
  14. package/dist/cli/{gate-evidence-ra0trg97.js → gate-evidence-cvkr2ybm.js} +2 -2
  15. package/dist/cli/{guardrail-explain-kghhhjky.js → guardrail-explain-64q268m0.js} +24 -24
  16. package/dist/cli/{guardrail-log-r72971jr.js → guardrail-log-gp01x3n1.js} +3 -3
  17. package/dist/cli/{guardrail-reset-1kq1m70y.js → guardrail-reset-z0t943fx.js} +23 -23
  18. package/dist/cli/{hive-promoter-82ygdw79.js → hive-promoter-vjb7y55n.js} +23 -23
  19. package/dist/cli/{index-rr1m7cc6.js → index-11z82cjy.js} +3 -3
  20. package/dist/cli/{index-k1cxfede.js → index-1d0p1v2q.js} +1 -1
  21. package/dist/cli/{index-1v13c6r0.js → index-2xm8hp34.js} +2 -2
  22. package/dist/cli/{index-w6agyrzs.js → index-5qdhf317.js} +1 -1
  23. package/dist/cli/{index-dm2ydm2b.js → index-5qhkd1fc.js} +1 -1
  24. package/dist/cli/{index-stcacf0k.js → index-88vt0941.js} +25 -25
  25. package/dist/cli/{index-zmgs43tw.js → index-8cd5abna.js} +1 -1
  26. package/dist/cli/{index-q5115jpe.js → index-90byps3b.js} +3 -3
  27. package/dist/cli/{index-xka1cq9k.js → index-9a2vvwk2.js} +1 -1
  28. package/dist/cli/{index-ahe4mn8t.js → index-a86t7pa9.js} +23 -23
  29. package/dist/cli/{index-zq40mkha.js → index-ae2kzm55.js} +4 -4
  30. package/dist/cli/{index-jct9kb50.js → index-ak936pwb.js} +1 -1
  31. package/dist/cli/{index-6ayk7a3q.js → index-egd6f37q.js} +1 -1
  32. package/dist/cli/{index-5r5s0dbb.js → index-gbshh8v2.js} +5 -5
  33. package/dist/cli/{index-amhr3swp.js → index-hphprp03.js} +1 -1
  34. package/dist/cli/{index-rpsmx4ke.js → index-hrza3045.js} +1 -1
  35. package/dist/cli/{index-peg6sftq.js → index-jqqhq9h6.js} +1 -1
  36. package/dist/cli/{index-rp6sfpwp.js → index-kaknnfaw.js} +1 -1
  37. package/dist/cli/{index-bga7w4rt.js → index-mybjc24z.js} +2 -2
  38. package/dist/cli/{index-hkqd9jz6.js → index-q7vtghff.js} +5 -5
  39. package/dist/cli/{index-b0qyb790.js → index-r93jbg90.js} +2 -2
  40. package/dist/cli/{index-x9wpvhpk.js → index-raqa5vnb.js} +1 -1
  41. package/dist/cli/{index-279xp2be.js → index-vww242dg.js} +1 -1
  42. package/dist/cli/{index-131ay7x1.js → index-vyjped9g.js} +18 -1
  43. package/dist/cli/{index-zvbn85q0.js → index-w06xcw6v.js} +3 -3
  44. package/dist/cli/{index-2wn8ww1e.js → index-ye8t9qq3.js} +59 -59
  45. package/dist/cli/{index-j2xcdbfd.js → index-yjkgrerq.js} +1 -1
  46. package/dist/cli/{index-8chh1c96.js → index-z3xbmp3x.js} +4 -4
  47. package/dist/cli/index.js +24 -24
  48. package/dist/cli/{knowledge-escalator-x0159cv7.js → knowledge-escalator-agfq92ps.js} +6 -6
  49. package/dist/cli/{knowledge-events-4879bjbz.js → knowledge-events-4krnrjdh.js} +4 -4
  50. package/dist/cli/{knowledge-store-zvstn7dy.js → knowledge-store-bd0380r4.js} +1 -1
  51. package/dist/cli/{knowledge-validator-k0q00zsj.js → knowledge-validator-b9wrs08q.js} +2 -2
  52. package/dist/cli/{mcp-tmr9kgrr.js → mcp-43m5e2bb.js} +1 -1
  53. package/dist/cli/{model-preflight-17y17gys.js → model-preflight-tb6ne377.js} +23 -23
  54. package/dist/cli/{pending-delegations-jzr2w62w.js → pending-delegations-0qbxpf68.js} +2 -2
  55. package/dist/cli/{pr-subscriptions-t867sq1q.js → pr-subscriptions-dek1sqh0.js} +1 -1
  56. package/dist/cli/{pr-workflow-gate-npgdhk7j.js → pr-workflow-gate-md8brvw1.js} +23 -23
  57. package/dist/cli/{scan-cursor-5zy5h556.js → scan-cursor-w333f57f.js} +2 -2
  58. package/dist/cli/{schema-80nb4z6k.js → schema-3r41ckef.js} +1 -1
  59. package/dist/cli/{scope-persistence-t2888gjf.js → scope-persistence-dthn7rxz.js} +5 -5
  60. package/dist/cli/{server-41f41q15.js → server-b0teb7vg.js} +23 -23
  61. package/dist/cli/{skill-generator-6kj1xzk8.js → skill-generator-474vdbar.js} +7 -7
  62. package/dist/cli/{snapshot-coordination-init-pbdzjv20.js → snapshot-coordination-init-wtydyah2.js} +23 -23
  63. package/dist/cli/{speckit-checkoff-4ppx68ks.js → speckit-checkoff-27mk0e41.js} +3 -3
  64. package/dist/cli/{workspace-snapshot-0q1n1xq5.js → workspace-snapshot-xwhhznt3.js} +3 -1
  65. package/dist/cli/{worktree-collision-ownership-hn1mgtta.js → worktree-collision-ownership-2mtmrdkp.js} +2 -2
  66. package/dist/cli/{worktree-isolation-w4nq6yzp.js → worktree-isolation-kgda5awq.js} +23 -23
  67. package/dist/hooks/pr-workflow-gate.d.ts +9 -4
  68. package/dist/index.js +6 -6
  69. 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.2",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","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",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},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"]},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.4",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",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},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"]},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
 
@@ -542,14 +542,14 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
542
542
  WHERE p.plan_id = ?
543
543
  AND qi.profile_id IS NULL
544
544
  LIMIT 1`).get(readablePlanId)??null}function buildExactStoragePlanId(identityHash){return`qa2-${identityHash}`}function hasAnyGatePatch(gates){return Object.values(gates).some((value)=>value!==void 0)}function verifyBoundIdentityBinding(binding,identity){if(binding.identity_hash!==identity.identityHash||binding.raw_swarm!==identity.swarm||binding.raw_title!==identity.title||binding.readable_plan_id!==identity.planId)throw Error(`QA gate profile identity binding is corrupt for swarm_id='${identity.swarm}' and plan_title='${identity.title}'`)}function lookupProfileForIdentityTx(db,identity){let binding=readIdentityBindingByHash(db,identity.identityHash);if(binding){verifyBoundIdentityBinding(binding,identity);let row=readProfileRowById(db,binding.profile_id);if(!row)throw Error(`QA gate profile identity binding points to missing profile_id=${binding.profile_id}`);return{kind:"bound",identity,profile:rowToProfileWithBinding(row,binding)}}let legacyRow=readUnboundLegacyProfileRowByReadablePlanId(db,identity.planId);if(legacyRow)return{kind:"unbound_legacy",identity,profile:rowToProfile(legacyRow)};return{kind:"missing",identity}}function createExactIdentityBindingTx(db,profileId,identity){db.run("INSERT INTO qa_gate_profile_identity (identity_hash, profile_id, raw_swarm, raw_title, readable_plan_id) VALUES (?, ?, ?, ?, ?)",[identity.identityHash,profileId,identity.swarm,identity.title,identity.planId])}function createExactProfileTx(db,identity,projectType,initialGates){let gatesJson=JSON.stringify({...DEFAULT_QA_GATES,...initialGates});db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[buildExactStoragePlanId(identity.identityHash),projectType??null,gatesJson]);let row=readProfileRowByPlanId(db,buildExactStoragePlanId(identity.identityHash));if(!row)throw Error(`Failed to create QA gate profile row for exact identity plan_id=${identity.planId}`);createExactIdentityBindingTx(db,row.id,identity);let binding=readIdentityBindingByHash(db,identity.identityHash);if(!binding)throw Error(`Failed to create QA gate profile identity binding for plan_id=${identity.planId}`);return rowToProfileWithBinding(row,binding)}function shouldAdoptLegacyProfile(identity,options){if(options.allowLegacyAdoption!==!0)return!1;return options.legacyAdoptionIdentity?.swarm===identity.swarm&&options.legacyAdoptionIdentity?.title===identity.title}function getProfile(directory,planId){if(!projectDbExists(directory))return null;let db=getProjectDb(directory),row=readProfileRowByPlanId(db,planId);return row?rowToProfile(row):null}function getProfileForIdentity(directory,identity){let lookup=getProfileLookupForIdentity(directory,identity);if(lookup.kind==="bound")return lookup.profile;if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);return null}function getProfileLookupForIdentity(directory,identity){let exact=buildProfileIdentity(identity);if(!projectDbExists(directory))return{kind:"missing",identity:exact};let db=getProjectDb(directory);return lookupProfileForIdentityTx(db,exact)}function hasAnyProfileWithEnabledGate(directory,gate){if(!projectDbExists(directory))return!1;let rows=getProjectDb(directory).query("SELECT gates FROM qa_gate_profile").all();for(let row of rows)try{if(JSON.parse(row.gates)?.[gate]===!0)return!0}catch(err){warn(`[qa-gate-profile] skipping unparseable qa_gate_profile row while checking gate "${gate}": ${err instanceof Error?err.message:String(err)}`)}return!1}function getOrCreateProfile(directory,planId,projectType,initialGates={}){let existing=_internals29.getProfile(directory,planId);if(existing)return existing;let db=getProjectDb(directory),seededGates={...DEFAULT_QA_GATES};for(let key of Object.keys(DEFAULT_QA_GATES))if(typeof initialGates[key]==="boolean")seededGates[key]=initialGates[key];let gatesJson=JSON.stringify(seededGates);try{withImmediateTransaction2(db,()=>{db.run("INSERT INTO qa_gate_profile (plan_id, project_type, gates) VALUES (?, ?, ?)",[planId,projectType??null,gatesJson])})}catch(err){if(!(err instanceof Error?err.message:String(err)).toLowerCase().includes("unique"))throw err}let after=_internals29.getProfile(directory,planId);if(!after)throw Error(`Failed to create or load QA gate profile for plan_id=${planId}`);return after}function getOrCreateProfileForIdentity(directory,identity,projectType,initialGates={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction2(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="bound")return lookup.profile;return createExactProfileTx(db,exact,projectType,initialGates)})}function setGates(directory,planId,gates){let db=getProjectDb(directory);return withImmediateTransaction2(db,()=>{let currentRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!currentRow)throw Error(`No QA gate profile found for plan_id=${planId} — call getOrCreateProfile first`);let current=rowToProfile(currentRow);if(current.locked_at!==null)throw Error("Cannot modify gates: QA gate profile is locked after critic approval");_internals29.afterSetGatesRead(current);let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE plan_id = ?",[JSON.stringify(merged),planId]);let updatedRow=db.query("SELECT * FROM qa_gate_profile WHERE plan_id = ?").get(planId);if(!updatedRow)throw Error(`Failed to re-read QA gate profile after update for plan_id=${planId}`);return rowToProfile(updatedRow)})}function setGatesForIdentity(directory,identity,gates,options={}){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction2(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")return createExactProfileTx(db,exact,options.projectType,gates);if(lookup.kind==="unbound_legacy")if(shouldAdoptLegacyProfile(exact,options)){if(createExactIdentityBindingTx(db,lookup.profile.id,exact),lookup=lookupProfileForIdentityTx(db,exact),lookup.kind!=="bound")throw Error(`Failed to adopt legacy QA gate profile for exact identity plan_id=${exact.planId}`)}else if(options.allowLegacyCollisionCreate===!0)return createExactProfileTx(db,exact,options.projectType,gates);else throw new QaGateProfileIdentityUnboundError(lookup.identity);let current=lookup.profile,currentRow=readProfileRowById(db,current.id);if(!currentRow)throw Error(`Failed to read QA gate profile row for profile_id=${current.id}`);if(_internals29.afterSetGatesForIdentityRead?.({directory,identity:exact,profileId:current.id,storagePlanId:currentRow.plan_id}),current.locked_at!==null){if(!hasAnyGatePatch(gates))return current;throw Error("Cannot modify gates: QA gate profile is locked after critic approval")}let merged={...current.gates};for(let key of Object.keys(gates)){let incoming=gates[key];if(incoming===void 0)continue;if(incoming===!1&&current.gates[key]===!0)throw Error(`Cannot disable gate '${key}': sessions can only ratchet tighter`);if(incoming===!0)merged[key]=!0}db.run("UPDATE qa_gate_profile SET gates = ? WHERE id = ?",[JSON.stringify(merged),current.id]);let updatedRow=readProfileRowById(db,current.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read QA gate profile after exact-identity update for plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function lockProfileForIdentity(directory,identity,snapshotSeq){let db=getProjectDb(directory),exact=buildProfileIdentity(identity);return withImmediateTransaction2(db,()=>{let lookup=lookupProfileForIdentityTx(db,exact);if(lookup.kind==="missing")throw Error(`No QA gate profile found for exact identity plan_id=${exact.planId} — cannot lock`);if(lookup.kind==="unbound_legacy")throw new QaGateProfileIdentityUnboundError(lookup.identity);if(lookup.profile.locked_at!==null)return lookup.profile;db.run("UPDATE qa_gate_profile SET locked_at = datetime('now'), locked_by_snapshot_seq = ? WHERE id = ?",[snapshotSeq,lookup.profile.id]);let updatedRow=readProfileRowById(db,lookup.profile.id),binding=readIdentityBindingByHash(db,exact.identityHash);if(!updatedRow||!binding)throw Error(`Failed to re-read locked QA gate profile for exact identity plan_id=${exact.planId}`);return rowToProfileWithBinding(updatedRow,binding)})}function computeProfileHash(profile){let payload=JSON.stringify({plan_id:profile.plan_id,identity_hash:profile.identity_hash,gates:profile.gates});return createHash13("sha256").update(payload).digest("hex")}function getEffectiveGates(profile,sessionOverrides){let merged={...profile.gates};for(let key of Object.keys(sessionOverrides))if(sessionOverrides[key]===!0)merged[key]=!0;return merged}var _internals29,DEFAULT_QA_GATES,QaGateProfileIdentityUnboundError;var init_qa_gate_profile=__esm(()=>{init_utils3();init_logger();init_durability();init_project_db();_internals29={getProfile,getProfileLookupForIdentity,getProfileForIdentity,getOrCreateProfile,getOrCreateProfileForIdentity,setGates,setGatesForIdentity,lockProfileForIdentity,getEffectiveGates,computeProfileHash,hasAnyProfileWithEnabledGate,afterSetGatesRead:()=>{},lastTxnSynchronous:-1},DEFAULT_QA_GATES={reviewer:!0,test_engineer:!0,council_mode:!1,sme_enabled:!0,critic_pre_plan:!0,hallucination_guard:!1,sast_enabled:!0,mutation_test:!1,phase_council:!1,drift_check:!0,final_council:!1};QaGateProfileIdentityUnboundError=class QaGateProfileIdentityUnboundError extends Error{identity;constructor(identity){super(`QA gate profile exists for readable plan_id='${identity.planId}' but is not exact-bound to swarm_id='${identity.swarm}' and plan_title='${identity.title}'. ${formatLegacyQaBindingRecovery(identity,"retry the blocked read-only or enforcement operation")}`);this.name="QaGateProfileIdentityUnboundError",this.identity=identity}}});var init_db=__esm(()=>{init_coordination_store();init_global_db();init_project_db();init_qa_gate_profile();init_sqlite_loader()});import*as fs12 from"node:fs";import*as path26 from"node:path";function sleepSync2(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function healthArtifactPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_HEALTH_FILE)}function readDelegationHealthArtifact(directory){let raw;try{raw=fs12.readFileSync(healthArtifactPath(directory),"utf-8")}catch{return null}try{let parsed=DelegationLedgerHealthSchema.safeParse(JSON.parse(raw));return parsed.success?parsed.data:null}catch{return null}}function writeDelegationHealthArtifact(directory,update){let base=readDelegationHealthArtifact(directory)??{schemaVersion:1,updatedAt:0,ledger:{bytes:0,limitBytes:MAX_RECOVERY_LEDGER_BYTES,pressurePct:0,band:"ok"},checkpoint:null,recovery:null,lastUncertainty:null,counts:{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:null},next={schemaVersion:1,updatedAt:Date.now(),ledger:update.ledger??base.ledger,checkpoint:update.checkpoint===void 0?base.checkpoint:update.checkpoint,recovery:update.recovery===void 0?base.recovery:update.recovery,lastUncertainty:update.lastUncertainty??base.lastUncertainty,counts:update.counts??base.counts,maintenance:update.maintenance===void 0?base.maintenance??null:update.maintenance};if(update.uncertainty)next.lastUncertainty=update.uncertainty;let parsed=DelegationLedgerHealthSchema.safeParse(next);if(!parsed.success)return null;try{fs12.mkdirSync(path26.resolve(directory,".swarm"),{recursive:!0});let target=healthArtifactPath(directory),tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;fs12.writeFileSync(tmp,`${JSON.stringify(parsed.data)}
545
- `,"utf-8");let lastError;for(let attempt=0;attempt<5;attempt++)try{_healthInternals.renameOnce(tmp,target),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<4)sleepSync2(15)}if(lastError!==void 0){try{fs12.rmSync(tmp,{force:!0})}catch{}return null}return parsed.data}catch{return null}}function recordDelegationRecoveryObservation(directory,observation){try{writeDelegationHealthArtifact(directory,{recovery:{source:observation.source,at:Date.now(),ok:observation.ok,...observation.reason?{reason:observation.reason}:{},...observation.repairHint?{repairHint:observation.repairHint}:{}},...observation.ok?{}:{uncertainty:{reason:observation.reason??"recovery failed",at:Date.now(),source:"recovery",...observation.repairHint?{repairHint:observation.repairHint}:{}}}})}catch{}}function appendDelegationMaintenanceObservation(directory,observation){try{let current=readDelegationHealthArtifact(directory)?.maintenance??null,section={lastRunAt:observation.at,lastOkAt:observation.status==="ok"?observation.at:current?.lastOkAt??null,lastFailure:observation.status==="failure"&&observation.reason?{reason:observation.reason,at:observation.at}:current?.lastFailure??null,lastContentionAt:observation.status==="contention"?observation.at:current?.lastContentionAt??null,lastSummary:observation.summary??current?.lastSummary??{sweptStale:0,released:0,renewed:0,retained:0},facts:[...current?.facts??[],...observation.facts].slice(-MAX_MAINTENANCE_FACTS)};writeDelegationHealthArtifact(directory,{maintenance:section})}catch{}}function collectDelegationLedgerHealth(directory,options){let artifact=readDelegationHealthArtifact(directory),ledgerBytes=0,ledgerExists=!1;try{ledgerBytes=fs12.statSync(validateSwarmPath(directory,"background-delegations.jsonl")).size,ledgerExists=!0}catch{ledgerExists=!1}if(!artifact&&!ledgerExists)return null;let limitBytes=options.ledgerLimitBytes,pressurePct=Math.min(100,Math.round(ledgerBytes/limitBytes*1000)/10),band=ledgerBytes>limitBytes?"fail-closed":ledgerBytes>options.highWaterBytes?"compact-overdue":ledgerBytes>options.lowWaterBytes?"nominal":"ok";return observeDelegationLedgerPressure({directory,pressurePct:pressurePct/100,band,uncertain:artifact?.lastUncertainty!=null}),{schemaVersion:1,updatedAt:artifact?.updatedAt??0,ledger:{bytes:ledgerBytes,limitBytes,pressurePct,band},checkpoint:artifact?.checkpoint??null,recovery:artifact?.recovery??null,lastUncertainty:artifact?.lastUncertainty??null,counts:artifact?.counts??{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:artifact?.maintenance??null}}var BACKGROUND_DELEGATIONS_HEALTH_FILE="background-delegations-health.json",MAX_RECOVERY_LEDGER_BYTES=4194304,DelegationCheckpointAuditSchema,CheckpointSectionSchema,RecoverySectionSchema,UncertaintySectionSchema,MAX_MAINTENANCE_FACTS=20,DelegationMaintenanceFactSchema,MaintenanceSectionSchema,DelegationLedgerHealthSchema,_healthInternals;var init_delegation_health=__esm(()=>{init_zod();init_learning_health();init_utils2();DelegationCheckpointAuditSchema=exports_external.object({dispatchCount:exports_external.number().int().nonnegative(),terminalsByStatus:exports_external.object({completed:exports_external.number().int().nonnegative(),error:exports_external.number().int().nonnegative(),cancelled:exports_external.number().int().nonnegative(),stale:exports_external.number().int().nonnegative()}).strict(),settledCount:exports_external.number().int().nonnegative(),preservedCount:exports_external.number().int().nonnegative(),lateTerminalCount:exports_external.number().int().nonnegative(),compactedTransitionCount:exports_external.number().int().nonnegative(),compactedRecordCount:exports_external.number().int().nonnegative(),firstDispatchAt:exports_external.number().int().nonnegative().nullable(),lastTerminalAt:exports_external.number().int().nonnegative().nullable(),lastCompactionAt:exports_external.number().int().nonnegative()}).strict(),CheckpointSectionSchema=exports_external.object({sequence:exports_external.number().int().positive(),createdAt:exports_external.number().int().nonnegative(),liveRecords:exports_external.number().int().nonnegative(),closedSummaries:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),audit:DelegationCheckpointAuditSchema}).strict(),RecoverySectionSchema=exports_external.object({source:exports_external.enum(["checkpoint+tail","checkpoint+ledger-suffix","legacy-ledger","unknown"]),at:exports_external.number().int().nonnegative(),ok:exports_external.boolean(),reason:exports_external.string().min(1).max(2000).optional(),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),UncertaintySectionSchema=exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative(),source:exports_external.string().min(1).max(256),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),DelegationMaintenanceFactSchema=exports_external.object({at:exports_external.number().int().nonnegative(),kind:exports_external.enum(["release","retained-ambiguity","retained-protected-legacy","lease-renewed","maintenance-failure","lock-contention"]),reservationId:exports_external.string().min(1).max(256).optional(),correlationId:exports_external.string().min(1).max(256).optional(),generation:exports_external.number().int().positive().optional(),reason:exports_external.string().min(1).max(2000)}).strict(),MaintenanceSectionSchema=exports_external.object({lastRunAt:exports_external.number().int().nonnegative(),lastOkAt:exports_external.number().int().nonnegative().nullable(),lastFailure:exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative()}).strict().nullable(),lastContentionAt:exports_external.number().int().nonnegative().nullable(),lastSummary:exports_external.object({sweptStale:exports_external.number().int().nonnegative(),released:exports_external.number().int().nonnegative(),renewed:exports_external.number().int().nonnegative(),retained:exports_external.number().int().nonnegative()}).strict(),facts:exports_external.array(DelegationMaintenanceFactSchema).max(MAX_MAINTENANCE_FACTS)}).strict(),DelegationLedgerHealthSchema=exports_external.object({schemaVersion:exports_external.literal(1),updatedAt:exports_external.number().int().nonnegative(),ledger:exports_external.object({bytes:exports_external.number().int().nonnegative(),limitBytes:exports_external.number().int().positive(),pressurePct:exports_external.number().min(0).max(100),band:exports_external.enum(["ok","nominal","compact-overdue","fail-closed"])}).strict(),checkpoint:CheckpointSectionSchema.nullable(),recovery:RecoverySectionSchema.nullable(),lastUncertainty:UncertaintySectionSchema.nullable(),counts:exports_external.object({activeOwners:exports_external.number().int().nonnegative(),pendingAdvisories:exports_external.number().int().nonnegative(),lateTerminals:exports_external.number().int().nonnegative(),orphanWorktreeOwners:exports_external.number().int().nonnegative()}).strict(),maintenance:MaintenanceSectionSchema.nullable().optional()}).strict();_healthInternals={renameOnce:(from,to)=>{fs12.renameSync(from,to)}}});import{createHash as createHash14}from"node:crypto";function resolveLaneAtomicDisposition(receipt){if(new Set(receipt.assignedReviewItemIds).size!==receipt.assignedReviewItemIds.length)return null;let acceptedAll=receipt.rejectedReviewItemIds.length===0&&receipt.acceptedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.acceptedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]),rejectedAll=receipt.acceptedReviewItemIds.length===0&&receipt.rejectedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.rejectedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]);return acceptedAll?"accepted":rejectedAll?"rejected":null}function encodePrReviewCollectionReceiptFooter(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);if(!payload)return null;let footer=`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(payload)}`;return footer.length<=MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS?footer:null}function buildPrReviewCollectionReceiptPayload(binding,result,receipt){let disposition=resolveLaneAtomicDisposition(receipt);if(!disposition)return null;let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse({schemaVersion:1,parentSessionId:binding.parentSessionId,batchId:binding.batchId??binding.callID,laneId:binding.laneId??binding.correlationId,mode:binding.mode,workflowLane:binding.workflowLane,outputDigest:result.digest,disposition,reviewItemIds:receipt.assignedReviewItemIds});if(!parsed.success)return null;return parsed.data}function projectPrReviewCollectionReceipt(payload){let assignedReviewItemIds=[...payload.reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:payload.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:payload.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function reviewItemDigest(reviewItemIds){return createHash14("sha256").update(JSON.stringify(reviewItemIds)).digest("hex")}function encodePrReviewCollectionReceiptShedMarker(payload){let marker={schemaVersion:1,parentSessionId:payload.parentSessionId,batchId:payload.batchId,laneId:payload.laneId,mode:payload.mode,workflowLane:payload.workflowLane,outputDigest:payload.outputDigest,disposition:payload.disposition,reviewItemCount:payload.reviewItemIds.length,reviewItemDigest:reviewItemDigest(payload.reviewItemIds)};return`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker)}`}function encodePrReviewCollectionReceiptShedMarkerFromReceipt(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);return payload?encodePrReviewCollectionReceiptShedMarker(payload):null}function parsePrReviewCollectionReceiptShedMarker(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),markerLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)),finalLine=lines.at(-1);if(markerLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptShedMarkerSchema.safeParse(decoded);if(!parsed.success)return null;let marker=parsed.data;return marker.parentSessionId===binding.parentSessionId&&marker.batchId===(binding.batchId??binding.callID)&&marker.laneId===(binding.laneId??binding.correlationId)&&marker.mode===binding.mode&&marker.workflowLane===binding.workflowLane&&marker.outputDigest===result.digest?marker:null}function projectPrReviewCollectionReceiptShedMarker(marker,reviewItemIds){if(marker.reviewItemCount!==reviewItemIds.length||marker.reviewItemDigest!==reviewItemDigest(reviewItemIds))return null;let assignedReviewItemIds=[...reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:marker.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:marker.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function parsePrReviewCollectionReceiptFooter(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),receiptLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)),finalLine=lines.at(-1);if(receiptLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse(decoded);if(!parsed.success)return null;let payload=parsed.data;return payload.parentSessionId===binding.parentSessionId&&payload.batchId===(binding.batchId??binding.callID)&&payload.laneId===(binding.laneId??binding.correlationId)&&payload.mode===binding.mode&&payload.workflowLane===binding.workflowLane&&payload.outputDigest===result.digest?payload:null}var PR_REVIEW_COLLECTION_RECEIPT_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_V1] ",PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_SHED_V1] ",MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS=65536,MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS=1e4,PrReviewCollectionReceiptPayloadSchema,PrReviewCollectionReceiptShedMarkerSchema;var init_pr_review_collection_receipt=__esm(()=>{init_zod();PrReviewCollectionReceiptPayloadSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemIds:exports_external.array(exports_external.string().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)}).strict().superRefine((payload,context)=>{if(new Set(payload.reviewItemIds).size!==payload.reviewItemIds.length)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"review item IDs must be unique"})}),PrReviewCollectionReceiptShedMarkerSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemCount:exports_external.number().int().positive().max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS),reviewItemDigest:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,shouldSkipSnapshot:()=>shouldSkipSnapshot,resolveRemoteUrlIdentityAsync:()=>resolveRemoteUrlIdentityAsync,resolveRemoteUrlIdentity:()=>resolveRemoteUrlIdentity,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentLocalHeadRefAsync:()=>resolveCurrentLocalHeadRefAsync,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,redactRemoteUrlIdentity:()=>redactRemoteUrlIdentity,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,isSwarmRuntimePath:()=>isSwarmRuntimePath,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,changedFilesSinceSnapshotAsync:()=>changedFilesSinceSnapshotAsync,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshotAsync:()=>captureWorkspaceSnapshotAsync,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals30});import*as child_process from"node:child_process";import{createHash as createHash15}from"node:crypto";import*as fs13 from"node:fs";import*as path27 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals30.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals30.bunSpawn([_internals30.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve17)=>{timeout=setTimeout(()=>resolve17({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals30.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals30.bunSpawn([_internals30.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals30.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve17)=>{timeout=setTimeout(()=>resolve17({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
545
+ `,"utf-8");let lastError;for(let attempt=0;attempt<5;attempt++)try{_healthInternals.renameOnce(tmp,target),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;if(attempt<4)sleepSync2(15)}if(lastError!==void 0){try{fs12.rmSync(tmp,{force:!0})}catch{}return null}return parsed.data}catch{return null}}function recordDelegationRecoveryObservation(directory,observation){try{writeDelegationHealthArtifact(directory,{recovery:{source:observation.source,at:Date.now(),ok:observation.ok,...observation.reason?{reason:observation.reason}:{},...observation.repairHint?{repairHint:observation.repairHint}:{}},...observation.ok?{}:{uncertainty:{reason:observation.reason??"recovery failed",at:Date.now(),source:"recovery",...observation.repairHint?{repairHint:observation.repairHint}:{}}}})}catch{}}function appendDelegationMaintenanceObservation(directory,observation){try{let current=readDelegationHealthArtifact(directory)?.maintenance??null,section={lastRunAt:observation.at,lastOkAt:observation.status==="ok"?observation.at:current?.lastOkAt??null,lastFailure:observation.status==="failure"&&observation.reason?{reason:observation.reason,at:observation.at}:current?.lastFailure??null,lastContentionAt:observation.status==="contention"?observation.at:current?.lastContentionAt??null,lastSummary:observation.summary??current?.lastSummary??{sweptStale:0,released:0,renewed:0,retained:0},facts:[...current?.facts??[],...observation.facts].slice(-MAX_MAINTENANCE_FACTS)};writeDelegationHealthArtifact(directory,{maintenance:section})}catch{}}function collectDelegationLedgerHealth(directory,options){let artifact=readDelegationHealthArtifact(directory),ledgerBytes=0,ledgerExists=!1;try{ledgerBytes=fs12.statSync(validateSwarmPath(directory,"background-delegations.jsonl")).size,ledgerExists=!0}catch{ledgerExists=!1}if(!artifact&&!ledgerExists)return null;let limitBytes=options.ledgerLimitBytes,pressurePct=Math.min(100,Math.round(ledgerBytes/limitBytes*1000)/10),band=ledgerBytes>limitBytes?"fail-closed":ledgerBytes>options.highWaterBytes?"compact-overdue":ledgerBytes>options.lowWaterBytes?"nominal":"ok";return observeDelegationLedgerPressure({directory,pressurePct:pressurePct/100,band,uncertain:artifact?.lastUncertainty!=null}),{schemaVersion:1,updatedAt:artifact?.updatedAt??0,ledger:{bytes:ledgerBytes,limitBytes,pressurePct,band},checkpoint:artifact?.checkpoint??null,recovery:artifact?.recovery??null,lastUncertainty:artifact?.lastUncertainty??null,counts:artifact?.counts??{activeOwners:0,pendingAdvisories:0,lateTerminals:0,orphanWorktreeOwners:0},maintenance:artifact?.maintenance??null}}var BACKGROUND_DELEGATIONS_HEALTH_FILE="background-delegations-health.json",MAX_RECOVERY_LEDGER_BYTES=4194304,DelegationCheckpointAuditSchema,CheckpointSectionSchema,RecoverySectionSchema,UncertaintySectionSchema,MAX_MAINTENANCE_FACTS=20,DelegationMaintenanceFactSchema,MaintenanceSectionSchema,DelegationLedgerHealthSchema,_healthInternals;var init_delegation_health=__esm(()=>{init_zod();init_learning_health();init_utils2();DelegationCheckpointAuditSchema=exports_external.object({dispatchCount:exports_external.number().int().nonnegative(),terminalsByStatus:exports_external.object({completed:exports_external.number().int().nonnegative(),error:exports_external.number().int().nonnegative(),cancelled:exports_external.number().int().nonnegative(),stale:exports_external.number().int().nonnegative()}).strict(),settledCount:exports_external.number().int().nonnegative(),preservedCount:exports_external.number().int().nonnegative(),lateTerminalCount:exports_external.number().int().nonnegative(),compactedTransitionCount:exports_external.number().int().nonnegative(),compactedRecordCount:exports_external.number().int().nonnegative(),firstDispatchAt:exports_external.number().int().nonnegative().nullable(),lastTerminalAt:exports_external.number().int().nonnegative().nullable(),lastCompactionAt:exports_external.number().int().nonnegative()}).strict(),CheckpointSectionSchema=exports_external.object({sequence:exports_external.number().int().positive(),createdAt:exports_external.number().int().nonnegative(),liveRecords:exports_external.number().int().nonnegative(),closedSummaries:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),audit:DelegationCheckpointAuditSchema}).strict(),RecoverySectionSchema=exports_external.object({source:exports_external.enum(["checkpoint+tail","checkpoint+ledger-suffix","legacy-ledger","unknown"]),at:exports_external.number().int().nonnegative(),ok:exports_external.boolean(),reason:exports_external.string().min(1).max(2000).optional(),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),UncertaintySectionSchema=exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative(),source:exports_external.string().min(1).max(256),repairHint:exports_external.string().min(1).max(2000).optional()}).strict(),DelegationMaintenanceFactSchema=exports_external.object({at:exports_external.number().int().nonnegative(),kind:exports_external.enum(["release","retained-ambiguity","retained-protected-legacy","lease-renewed","maintenance-failure","lock-contention"]),reservationId:exports_external.string().min(1).max(256).optional(),correlationId:exports_external.string().min(1).max(256).optional(),generation:exports_external.number().int().positive().optional(),reason:exports_external.string().min(1).max(2000)}).strict(),MaintenanceSectionSchema=exports_external.object({lastRunAt:exports_external.number().int().nonnegative(),lastOkAt:exports_external.number().int().nonnegative().nullable(),lastFailure:exports_external.object({reason:exports_external.string().min(1).max(2000),at:exports_external.number().int().nonnegative()}).strict().nullable(),lastContentionAt:exports_external.number().int().nonnegative().nullable(),lastSummary:exports_external.object({sweptStale:exports_external.number().int().nonnegative(),released:exports_external.number().int().nonnegative(),renewed:exports_external.number().int().nonnegative(),retained:exports_external.number().int().nonnegative()}).strict(),facts:exports_external.array(DelegationMaintenanceFactSchema).max(MAX_MAINTENANCE_FACTS)}).strict(),DelegationLedgerHealthSchema=exports_external.object({schemaVersion:exports_external.literal(1),updatedAt:exports_external.number().int().nonnegative(),ledger:exports_external.object({bytes:exports_external.number().int().nonnegative(),limitBytes:exports_external.number().int().positive(),pressurePct:exports_external.number().min(0).max(100),band:exports_external.enum(["ok","nominal","compact-overdue","fail-closed"])}).strict(),checkpoint:CheckpointSectionSchema.nullable(),recovery:RecoverySectionSchema.nullable(),lastUncertainty:UncertaintySectionSchema.nullable(),counts:exports_external.object({activeOwners:exports_external.number().int().nonnegative(),pendingAdvisories:exports_external.number().int().nonnegative(),lateTerminals:exports_external.number().int().nonnegative(),orphanWorktreeOwners:exports_external.number().int().nonnegative()}).strict(),maintenance:MaintenanceSectionSchema.nullable().optional()}).strict();_healthInternals={renameOnce:(from,to)=>{fs12.renameSync(from,to)}}});import{createHash as createHash14}from"node:crypto";function resolveLaneAtomicDisposition(receipt){if(new Set(receipt.assignedReviewItemIds).size!==receipt.assignedReviewItemIds.length)return null;let acceptedAll=receipt.rejectedReviewItemIds.length===0&&receipt.acceptedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.acceptedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]),rejectedAll=receipt.acceptedReviewItemIds.length===0&&receipt.rejectedReviewItemIds.length===receipt.assignedReviewItemIds.length&&receipt.rejectedReviewItemIds.every((itemId,index)=>itemId===receipt.assignedReviewItemIds[index]);return acceptedAll?"accepted":rejectedAll?"rejected":null}function encodePrReviewCollectionReceiptFooter(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);if(!payload)return null;let footer=`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(payload)}`;return footer.length<=MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS?footer:null}function buildPrReviewCollectionReceiptPayload(binding,result,receipt){let disposition=resolveLaneAtomicDisposition(receipt);if(!disposition)return null;let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse({schemaVersion:1,parentSessionId:binding.parentSessionId,batchId:binding.batchId??binding.callID,laneId:binding.laneId??binding.correlationId,mode:binding.mode,workflowLane:binding.workflowLane,outputDigest:result.digest,disposition,reviewItemIds:receipt.assignedReviewItemIds});if(!parsed.success)return null;return parsed.data}function projectPrReviewCollectionReceipt(payload){let assignedReviewItemIds=[...payload.reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:payload.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:payload.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function reviewItemDigest(reviewItemIds){return createHash14("sha256").update(JSON.stringify(reviewItemIds)).digest("hex")}function encodePrReviewCollectionReceiptShedMarker(payload){let marker={schemaVersion:1,parentSessionId:payload.parentSessionId,batchId:payload.batchId,laneId:payload.laneId,mode:payload.mode,workflowLane:payload.workflowLane,outputDigest:payload.outputDigest,disposition:payload.disposition,reviewItemCount:payload.reviewItemIds.length,reviewItemDigest:reviewItemDigest(payload.reviewItemIds)};return`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker)}`}function encodePrReviewCollectionReceiptShedMarkerFromReceipt(binding,result,receipt){let payload=buildPrReviewCollectionReceiptPayload(binding,result,receipt);return payload?encodePrReviewCollectionReceiptShedMarker(payload):null}function parsePrReviewCollectionReceiptShedMarker(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),markerLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)),finalLine=lines.at(-1);if(markerLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptShedMarkerSchema.safeParse(decoded);if(!parsed.success)return null;let marker=parsed.data;return marker.parentSessionId===binding.parentSessionId&&marker.batchId===(binding.batchId??binding.callID)&&marker.laneId===(binding.laneId??binding.correlationId)&&marker.mode===binding.mode&&marker.workflowLane===binding.workflowLane&&marker.outputDigest===result.digest?marker:null}function projectPrReviewCollectionReceiptShedMarker(marker,reviewItemIds){if(marker.reviewItemCount!==reviewItemIds.length||marker.reviewItemDigest!==reviewItemDigest(reviewItemIds))return null;let assignedReviewItemIds=[...reviewItemIds];return{assignedReviewItemIds,acceptedReviewItemIds:marker.disposition==="accepted"?[...assignedReviewItemIds]:[],rejectedReviewItemIds:marker.disposition==="rejected"?[...assignedReviewItemIds]:[]}}function parsePrReviewCollectionReceiptFooter(binding,result){if(!result.text)return null;let lines=result.text.split(/\r?\n/),receiptLines=lines.filter((line)=>line.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)),finalLine=lines.at(-1);if(receiptLines.length!==1||!finalLine?.startsWith(PR_REVIEW_COLLECTION_RECEIPT_PREFIX)||finalLine.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS)return null;let decoded;try{decoded=JSON.parse(finalLine.slice(PR_REVIEW_COLLECTION_RECEIPT_PREFIX.length))}catch{return null}let parsed=PrReviewCollectionReceiptPayloadSchema.safeParse(decoded);if(!parsed.success)return null;let payload=parsed.data;return payload.parentSessionId===binding.parentSessionId&&payload.batchId===(binding.batchId??binding.callID)&&payload.laneId===(binding.laneId??binding.correlationId)&&payload.mode===binding.mode&&payload.workflowLane===binding.workflowLane&&payload.outputDigest===result.digest?payload:null}var PR_REVIEW_COLLECTION_RECEIPT_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_V1] ",PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX="[PR_REVIEW_COLLECTION_RECEIPT_SHED_V1] ",MAX_PR_REVIEW_COLLECTION_RECEIPT_CHARS=65536,MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS=1e4,PrReviewCollectionReceiptPayloadSchema,PrReviewCollectionReceiptShedMarkerSchema;var init_pr_review_collection_receipt=__esm(()=>{init_zod();PrReviewCollectionReceiptPayloadSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemIds:exports_external.array(exports_external.string().min(1).max(160)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)}).strict().superRefine((payload,context)=>{if(new Set(payload.reviewItemIds).size!==payload.reviewItemIds.length)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"review item IDs must be unique"})}),PrReviewCollectionReceiptShedMarkerSchema=exports_external.object({schemaVersion:exports_external.literal(1),parentSessionId:exports_external.string().min(1).max(256),batchId:exports_external.string().min(1).max(120),laneId:exports_external.string().min(1).max(120),mode:exports_external.enum(["swarm-pr-review:reviewer","swarm-pr-review:critic"]),workflowLane:exports_external.string().min(1).max(120),outputDigest:exports_external.string().regex(/^[a-f0-9]{64}$/),disposition:exports_external.enum(["accepted","rejected"]),reviewItemCount:exports_external.number().int().positive().max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS),reviewItemDigest:exports_external.string().regex(/^[a-f0-9]{64}$/)}).strict()});var exports_workspace_snapshot={};__export(exports_workspace_snapshot,{workspaceSnapshotMatches:()=>workspaceSnapshotMatches,switchPrFeedbackTrackingCandidateAsync:()=>switchPrFeedbackTrackingCandidateAsync,shouldSkipSnapshot:()=>shouldSkipSnapshot,resolveRemoteUrlIdentityAsync:()=>resolveRemoteUrlIdentityAsync,resolveRemoteUrlIdentity:()=>resolveRemoteUrlIdentity,resolveRemoteRefsContainingHeadAsync:()=>resolveRemoteRefsContainingHeadAsync,resolveRemoteRefsContainingHead:()=>resolveRemoteRefsContainingHead,resolvePrWorkflowRevisionDigestDetailedAsync:()=>resolvePrWorkflowRevisionDigestDetailedAsync,resolvePrWorkflowRevisionDigestDetailed:()=>resolvePrWorkflowRevisionDigestDetailed,resolvePrWorkflowRevisionDigestAsync:()=>resolvePrWorkflowRevisionDigestAsync,resolvePrWorkflowRevisionDigest:()=>resolvePrWorkflowRevisionDigest,resolvePrReviewDiffStatsAsync:()=>resolvePrReviewDiffStatsAsync,resolvePrReviewDiffStats:()=>resolvePrReviewDiffStats,resolvePrFeedbackTrackingCandidatesAsync:()=>resolvePrFeedbackTrackingCandidatesAsync,resolveIsWorkingTreeCleanAsync:()=>resolveIsWorkingTreeCleanAsync,resolveIsWorkingTreeClean:()=>resolveIsWorkingTreeClean,resolveIsExactSingleChildCommitAsync:()=>resolveIsExactSingleChildCommitAsync,resolveIsExactSingleChildCommit:()=>resolveIsExactSingleChildCommit,resolveGitControlStateDigestAsync:()=>resolveGitControlStateDigestAsync,resolveGitControlStateDigest:()=>resolveGitControlStateDigest,resolveExactRemoteBranchHeadAsync:()=>resolveExactRemoteBranchHeadAsync,resolveExactRemoteBranchHead:()=>resolveExactRemoteBranchHead,resolveExactMergeBaseAsync:()=>resolveExactMergeBaseAsync,resolveExactMergeBase:()=>resolveExactMergeBase,resolveCurrentUpstreamRemoteRef:()=>resolveCurrentUpstreamRemoteRef,resolveCurrentUpstreamPushTargetAsync:()=>resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamPushTarget:()=>resolveCurrentUpstreamPushTarget,resolveCurrentLocalHeadRefAsync:()=>resolveCurrentLocalHeadRefAsync,resolveCurrentGitHeadAsync:()=>resolveCurrentGitHeadAsync,resolveCurrentGitHead:()=>resolveCurrentGitHead,resolveCommitCountSinceAsync:()=>resolveCommitCountSinceAsync,resolveCommitCountSince:()=>resolveCommitCountSince,redactRemoteUrlIdentity:()=>redactRemoteUrlIdentity,readGitTextAtRevision:()=>readGitTextAtRevision,parsePorcelainV2Snapshot:()=>parsePorcelainV2Snapshot,parsePorcelainPaths:()=>parsePorcelainPaths,isSwarmRuntimePath:()=>isSwarmRuntimePath,digest:()=>digest,compareWorkspaceSnapshots:()=>compareWorkspaceSnapshots,compareWorkspaceSnapshot:()=>compareWorkspaceSnapshot,committedFilesBetween:()=>committedFilesBetween,changedFilesSinceSnapshotAsync:()=>changedFilesSinceSnapshotAsync,changedFilesSinceSnapshot:()=>changedFilesSinceSnapshot,captureWorkspaceSnapshotAsync:()=>captureWorkspaceSnapshotAsync,captureWorkspaceSnapshot:()=>captureWorkspaceSnapshot,_internals:()=>_internals30});import*as child_process from"node:child_process";import{createHash as createHash15}from"node:crypto";import*as fs13 from"node:fs";import*as path27 from"node:path";async function readBoundedGitOutput(stream,maxBytes,onOverflow){let reader=stream.getReader(),chunks=[],totalBytes=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-totalBytes;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining));return onOverflow(),{text:"",truncated:!0}}chunks.push(value),totalBytes+=value.byteLength}let joined=new Uint8Array(totalBytes),offset=0;for(let chunk of chunks)joined.set(chunk,offset),offset+=chunk.byteLength;return{text:new TextDecoder().decode(joined),truncated:!1}}finally{try{await reader.cancel()}catch{}try{reader.releaseLock()}catch{}}}function runGit(directory,args2,timeoutMs=GIT_SNAPSHOT_TIMEOUT_MS){let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0)return null;return typeof result.stdout==="string"?result.stdout.trimEnd():null}async function runGitAsync(directory,args2,timeoutMs=_internals30.gitTimeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,killProcessTree:!0};proc=_internals30.bunSpawn([_internals30.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow),readBoundedGitOutput(proc.stderr,GIT_SNAPSHOT_MAX_BUFFER,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve17)=>{timeout=setTimeout(()=>resolve17({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout"||overflowed||result.exitCode!==0||result.stdout.truncated||result.stderr.truncated)return null;return result.stdout.text.trimEnd()}catch{return null}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function runGitDetailed(directory,args2,timeoutMs){let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,...args2],{cwd:directory,encoding:"utf-8",timeout:timeoutMs,maxBuffer:_internals30.gitSnapshotMaxBuffer,stdio:["ignore","pipe","pipe"]}),errorCode=result.error?.code;if(errorCode==="ENOBUFS")return{ok:!1,reason:"buffer-truncated"};if(errorCode==="ETIMEDOUT")return{ok:!1,reason:"timeout"};if(result.error||result.status!==0||typeof result.stdout!=="string")return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.trimEnd()}}async function runGitAsyncDetailed(directory,args2,timeoutMs){let proc,timeout;try{let options={cwd:directory,stdin:"ignore",stdout:"pipe",stderr:"pipe",killProcessTree:!0};proc=_internals30.bunSpawn([_internals30.resolveGitExecutable(),"-C",directory,...args2],options);let overflowed=!1,stopOverflow=()=>{overflowed=!0;try{proc?.kill("SIGKILL")}catch{}},maxBuffer=_internals30.gitSnapshotMaxBuffer,completed=Promise.all([proc.exited,readBoundedGitOutput(proc.stdout,maxBuffer,stopOverflow),readBoundedGitOutput(proc.stderr,maxBuffer,stopOverflow)]),result=await Promise.race([completed.then(([exitCode,stdout,stderr])=>({kind:"completed",exitCode,stdout,stderr})),new Promise((resolve17)=>{timeout=setTimeout(()=>resolve17({kind:"timeout"}),timeoutMs)})]);if(result.kind==="timeout")return{ok:!1,reason:"timeout"};if(overflowed||result.stdout.truncated||result.stderr.truncated)return{ok:!1,reason:"buffer-truncated"};if(result.exitCode!==0)return{ok:!1,reason:"git-failed"};return{ok:!0,text:result.stdout.text.trimEnd()}}catch{return{ok:!1,reason:"git-failed"}}finally{if(timeout)clearTimeout(timeout);try{proc?.kill("SIGKILL")}catch{}}}function readGitTextAtRevision(directory,revision,relativePath){if(!isSafeGitRevisionToken(revision)||!/^\.?(?:[A-Za-z0-9][A-Za-z0-9._-]*\/)*[A-Za-z0-9][A-Za-z0-9._-]*$/.test(relativePath)||relativePath.split("/").includes(".."))return null;let result=_internals30.spawnSync(_internals30.resolveGitExecutable(),["-C",directory,"show",`${revision}:${relativePath}`],{cwd:directory,encoding:"utf-8",timeout:GIT_SNAPSHOT_TIMEOUT_MS,maxBuffer:GIT_SNAPSHOT_MAX_BUFFER,stdio:["ignore","pipe","pipe"]});if(result.error||result.status!==0||typeof result.stdout!=="string")return null;return result.stdout}function resolveCurrentGitHead(directory){return runGit(directory,["rev-parse","--verify","HEAD^{commit}"])}async function resolveCurrentGitHeadAsync(directory){return await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"])}function resolveExactMergeBase(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=runGit(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}async function resolveExactMergeBaseAsync(directory,baseRef,prHeadSha){if(!isSafeGitRevisionToken(baseRef)||!isSafeGitRevisionToken(prHeadSha))return null;let mergeBase=await runGitAsync(directory,["merge-base","--",baseRef,prHeadSha]);return mergeBase&&/^[0-9a-f]{6,64}$/i.test(mergeBase)?mergeBase:null}function resolvePrReviewDiffStats(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=runGit(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
546
546
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=runGit(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
547
547
  `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}async function resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha){if(!isSafeGitRevisionToken(baseSha)||!isSafeGitRevisionToken(prHeadSha))return null;let range=`${baseSha}...${prHeadSha}`,output=await runGitAsync(directory,["diff","--no-renames","--numstat",range]);if(output===null)return null;let changedLines=0,changedFiles=0;for(let line of output.split(`
548
548
  `)){let trimmed=line.trim();if(trimmed.length===0)continue;let fields=trimmed.split("\t");if(fields.length<3)return null;let added=fields[0]==="-"?0:Number.parseInt(fields[0],10),deleted=fields[1]==="-"?0:Number.parseInt(fields[1],10);if(Number.isNaN(added)||Number.isNaN(deleted))return null;changedFiles+=1,changedLines+=added+deleted}let rawOutput=await runGitAsync(directory,["diff","--raw",range]);if(rawOutput===null)return null;let hasSubmoduleChange=rawOutput.split(`
549
549
  `).some((line)=>GITLINK_MODE_PATTERN.test(line.trim()));return{changedLines,changedFiles,hasSubmoduleChange}}function isSafeGitRevisionToken(value){return/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")}function resolveCurrentUpstreamRemoteRef(directory){let upstream=runGit(directory,["rev-parse","--symbolic-full-name","@{upstream}"]);if(!upstream?.startsWith("refs/remotes/")||upstream.endsWith("/HEAD"))return null;return upstream}function resolveCurrentUpstreamPushTarget(directory){let localBranchRef=runGit(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=runGit(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentUpstreamPushTargetAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);if(!localBranchRef?.startsWith("refs/heads/"))return null;let encoded=await runGitAsync(directory,["for-each-ref","--format=%(upstream:remotename)%00%(upstream:remoteref)%00%(upstream)",localBranchRef]);if(!encoded)return null;let[remoteName,remoteBranchRef,remoteTrackingRef,...extras]=encoded.split("\x00");if(extras.length>0||!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef?.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef)||!remoteTrackingRef?.startsWith("refs/remotes/")||remoteTrackingRef.endsWith("/HEAD"))return null;return{remoteName,remoteBranchRef,remoteTrackingRef}}async function resolveCurrentLocalHeadRefAsync(directory){let localBranchRef=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]);return localBranchRef?.startsWith("refs/heads/")?localBranchRef:null}function resolveExactRemoteBranchHead(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=runGit(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}async function resolveExactRemoteBranchHeadAsync(directory,remoteName,remoteBranchRef){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName)||!remoteBranchRef.startsWith("refs/heads/")||remoteBranchRef==="refs/heads/"||/[\s;&|<>`]/.test(remoteBranchRef))return null;let output=await runGitAsync(directory,["ls-remote","--exit-code","--heads",remoteName,remoteBranchRef],20000);if(!output)return null;let rows=output.split(/\r?\n/).filter(Boolean);if(rows.length!==1)return null;let[objectName,refName,...extras]=rows[0].split(/\s+/);if(extras.length>0||refName!==remoteBranchRef||!objectName||!(/^[0-9a-f]{40}$/i.test(objectName)||/^[0-9a-f]{64}$/i.test(objectName)))return null;return objectName}function redactRemoteUrlIdentity(url2,maxChars){let cap=(value)=>value.length>maxChars?value.slice(0,maxChars):value,stripQueryAndFragment=(value)=>{let cut=[value.indexOf("?"),value.indexOf("#")].filter((index)=>index>=0).sort((a,b)=>a-b)[0];return cut===void 0?value:`${value.slice(0,cut)}?…`},trimmed=url2.trim(),urlForm=trimmed.match(/^([A-Za-z][A-Za-z0-9+.-]*):\/\/(.*)$/);if(urlForm){let[,scheme,rest]=urlForm,authorityEnd=rest.indexOf("/"),authority=authorityEnd>=0?rest.slice(0,authorityEnd):rest,pathAndAfter=authorityEnd>=0?rest.slice(authorityEnd):"",at=authority.lastIndexOf("@"),redactedAuthority=at>=0?`***${authority.slice(at)}`:authority;return cap(`${scheme}://${redactedAuthority}${stripQueryAndFragment(pathAndAfter)}`)}let scpForm=trimmed.match(/^([^/@]+)@([^/@]+):(\S.*)$/);if(scpForm){let[,,host,path28]=scpForm;return cap(`***@${host}:${stripQueryAndFragment(path28)}`)}return cap(stripQueryAndFragment(trimmed))}function resolveRemoteUrlIdentity(directory,remoteName,maxChars=200){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName))return null;let output=runGit(directory,["remote","get-url","--push",remoteName]);if(!output)return null;let url2=output.split(/\r?\n/).filter(Boolean)[0];if(!url2)return null;return redactRemoteUrlIdentity(url2,maxChars)}async function resolveRemoteUrlIdentityAsync(directory,remoteName,maxChars=200){if(!remoteName||remoteName.startsWith("-")||/[\s;&|<>`]/.test(remoteName))return null;let output=await runGitAsync(directory,["remote","get-url","--push",remoteName]);if(!output)return null;let url2=output.split(/\r?\n/).filter(Boolean)[0];if(!url2)return null;return redactRemoteUrlIdentity(url2,maxChars)}function resolveGitControlStateDigest(directory){let head=runGit(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=runGit(directory,["symbolic-ref","--quiet","HEAD"]),upstream=resolveCurrentUpstreamPushTarget(directory),refs=runGit(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=runGit(directory,["config","--null","--show-origin","--show-scope","--list"]),index=runGit(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}async function resolveGitControlStateDigestAsync(directory){let head=await runGitAsync(directory,["rev-parse","--verify","HEAD^{commit}"]),symbolicHead=await runGitAsync(directory,["symbolic-ref","--quiet","HEAD"]),upstream=await resolveCurrentUpstreamPushTargetAsync(directory),refs=await runGitAsync(directory,["for-each-ref","--format=%(refname)%00%(objectname)","refs/heads","refs/remotes","refs/tags"]),config2=await runGitAsync(directory,["config","--null","--show-origin","--show-scope","--list"]),index=await runGitAsync(directory,["ls-files","--stage","-z"]);if(head===null||symbolicHead===null||!upstream||refs===null||config2===null||index===null)return null;return digest(`head\x00${head}\x00symbolic\x00${symbolicHead}\x00upstream\x00${upstream.remoteName}\x00${upstream.remoteBranchRef}\x00${upstream.remoteTrackingRef}\x00refs\x00${refs}\x00config\x00${config2}\x00index\x00${index}`)}function resolveIsWorkingTreeClean(directory){let status=runGit(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}async function resolveIsWorkingTreeCleanAsync(directory){let status=await runGitAsync(directory,["status","--porcelain=v1","--untracked-files=all"]);return status===null?null:status.length===0}function resolveCommitCountSince(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=runGit(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}async function resolveCommitCountSinceAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let output=await runGitAsync(directory,["rev-list","--count","--ancestry-path",`${baseHeadSha}..${currentHeadSha}`,"--"]);if(!output||!/^\d+$/.test(output))return null;let count=Number(output);return Number.isSafeInteger(count)?count:null}function resolveIsExactSingleChildCommit(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=runGit(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=runGit(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=runGit(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}async function resolveIsExactSingleChildCommitAsync(directory,baseHeadSha,currentHeadSha){if(!isSafeGitRevisionToken(baseHeadSha)||!isSafeGitRevisionToken(currentHeadSha))return null;let base=await runGitAsync(directory,["rev-parse","--verify",`${baseHeadSha}^{commit}`,"--"]),current=await runGitAsync(directory,["rev-parse","--verify",`${currentHeadSha}^{commit}`,"--"]);if(!base||!current)return null;let commitAndParents=await runGitAsync(directory,["rev-list","--parents","-n","1",current]);if(commitAndParents===null)return null;let fields=commitAndParents.trim().split(/\s+/);return fields.length===2&&fields[0]?.toLowerCase()===current.toLowerCase()&&fields[1]?.toLowerCase()===base.toLowerCase()}function resolveRemoteRefsContainingHead(directory,headSha){let output=runGit(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolveRemoteRefsContainingHeadAsync(directory,headSha){let output=await runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)","refs/remotes"]);if(output===null)return null;return output.split(/\r?\n/).map((line)=>line.trim().split("\t")).filter(([ref,objectName])=>ref?.startsWith("refs/remotes/")&&!ref.endsWith("/HEAD")&&objectName?.toLowerCase()===headSha.toLowerCase()).map(([ref])=>ref)}async function resolvePrFeedbackTrackingCandidatesAsync(directory,headSha){let[localOutput,remoteRefs]=await Promise.all([runGitAsync(directory,["for-each-ref","--format=%(refname)%09%(objectname)%09%(upstream)","refs/heads"]),resolveRemoteRefsContainingHeadAsync(directory,headSha)]);if(localOutput===null||remoteRefs===null)return null;let exactRemoteRefs=new Set(remoteRefs);return{local:localOutput.split(/\r?\n/).map((line)=>line.trim().split("\t")).flatMap(([ref,objectName,upstream,...extras])=>{if(extras.length>0||!ref?.startsWith("refs/heads/")||objectName?.toLowerCase()!==headSha.toLowerCase()||!upstream?.startsWith("refs/remotes/")||!exactRemoteRefs.has(upstream))return[];return[{kind:"local",branchName:ref.slice(11),remoteTrackingRef:upstream}]}),remote:remoteRefs.map((remoteTrackingRef)=>({kind:"remote",remoteTrackingRef}))}}async function switchPrFeedbackTrackingCandidateAsync(directory,candidate){let args2=candidate.kind==="local"?["switch","--no-guess","--",candidate.branchName]:["switch","--track","--",candidate.remoteTrackingRef];return await runGitAsync(directory,args2)!==null}function revisionDigestGitCallFailure(call,result){let description=result.reason==="timeout"?"timed out":result.reason==="buffer-truncated"?"output exceeded the bounded buffer":"failed";return{ok:!1,reason:result.reason,detail:`git ${call} ${description}`}}function resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha){let projectRoot=path27.resolve(directory),baseHeadResult=runGitDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals30.gitTimeoutMs);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);let diffResult=runGitDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals30.revisionEnumerationTimeoutMs);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);let porcelainResult=runGitDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals30.revisionEnumerationTimeoutMs);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals30.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals30.revisionMaxFiles}`};let hash2=createHash15("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0;for(let relativePath of changedPaths){let resolvedPath=path27.resolve(projectRoot,relativePath),relativeToRoot=path27.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path27.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=fs13.lstatSync(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${fs13.readlinkSync(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals30.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals30.revisionMaxTotalBytes} at ${relativePath}`};try{hash2.update(`file\x00${stats2.mode}\x00`),hash2.update(_internals30.readChangedFileSync(resolvedPath)),hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}}return{ok:!0,digest:hash2.digest("hex")}}function resolvePrWorkflowRevisionDigest(directory,baseHeadSha){let result=resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);return result.ok?result.digest:null}async function resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha){let projectRoot=path27.resolve(directory),[baseHeadResult,diffResult,porcelainResult]=await Promise.all([runGitAsyncDetailed(projectRoot,["rev-parse","--verify",`${baseHeadSha}^{commit}`],_internals30.gitTimeoutMs),runGitAsyncDetailed(projectRoot,["diff","--no-ext-diff","--name-only","-z",baseHeadSha],_internals30.revisionEnumerationTimeoutMs),runGitAsyncDetailed(projectRoot,["status","--porcelain=v1","-z","--untracked-files=all"],_internals30.revisionEnumerationTimeoutMs)]);if(!baseHeadResult.ok)return revisionDigestGitCallFailure("rev-parse --verify",baseHeadResult);if(!diffResult.ok)return revisionDigestGitCallFailure("diff --name-only",diffResult);if(!porcelainResult.ok)return revisionDigestGitCallFailure("status --porcelain",porcelainResult);let porcelainPaths=parsePorcelainPaths(porcelainResult.text);if(!porcelainPaths)return{ok:!1,reason:"git-failed",detail:"malformed git status --porcelain=v1 output"};let changedPaths=[...new Set([...parseNulPaths(diffResult.text),...porcelainPaths])].sort((left,right)=>left.localeCompare(right));if(changedPaths.length>_internals30.revisionMaxFiles)return{ok:!1,reason:"file-cap",detail:`${changedPaths.length} changed paths exceed the cap of ${_internals30.revisionMaxFiles}`};let hash2=createHash15("sha256");hash2.update(`base\x00${baseHeadResult.text}\x00`);let totalBytes=0,chunksSinceYield=0;for(let relativePath of changedPaths){let resolvedPath=path27.resolve(projectRoot,relativePath),relativeToRoot=path27.relative(projectRoot,resolvedPath);if(!relativeToRoot||relativeToRoot.startsWith("..")||path27.isAbsolute(relativeToRoot))return{ok:!1,reason:"containment",detail:`path escapes the project root: ${relativePath}`};hash2.update(`path\x00${relativePath}\x00`);let stats2;try{stats2=await fs13.promises.lstat(resolvedPath)}catch(error49){if(error49.code==="ENOENT"){hash2.update("deleted\x00");continue}return{ok:!1,reason:"read-failed",detail:`lstat failed for ${relativePath}`}}if(stats2.isSymbolicLink())try{hash2.update(`symlink\x00${await fs13.promises.readlink(resolvedPath)}\x00`);continue}catch{return{ok:!1,reason:"read-failed",detail:`readlink failed for ${relativePath}`}}if(!stats2.isFile()){hash2.update(`node\x00${stats2.mode}\x00`);continue}if(totalBytes+=stats2.size,totalBytes>_internals30.revisionMaxTotalBytes)return{ok:!1,reason:"byte-cap",detail:`accumulated content bytes ${totalBytes} exceed the cap of ${_internals30.revisionMaxTotalBytes} at ${relativePath}`};hash2.update(`file\x00${stats2.mode}\x00`);let handle;try{handle=await fs13.promises.open(resolvedPath,"r");let buffer=Buffer.allocUnsafe(REVISION_READ_CHUNK_BYTES);for(let position=0;position<stats2.size;){let length=Math.min(REVISION_READ_CHUNK_BYTES,stats2.size-position),{bytesRead}=await handle.read(buffer,0,length,position);if(bytesRead<=0)return{ok:!1,reason:"read-failed",detail:`short read for ${relativePath}`};if(hash2.update(buffer.subarray(0,bytesRead)),position+=bytesRead,chunksSinceYield++,chunksSinceYield>=REVISION_YIELD_EVERY_CHUNKS)chunksSinceYield=0,await _internals30.yieldControl()}hash2.update("\x00")}catch{return{ok:!1,reason:"read-failed",detail:`read failed for ${relativePath}`}}finally{await handle?.close().catch(()=>{return})}}return{ok:!0,digest:hash2.digest("hex")}}async function resolvePrWorkflowRevisionDigestAsync(directory,baseHeadSha){let result=await resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha);return result.ok?result.digest:null}function parseNulPaths(output){return output.split("\x00").filter((entry)=>entry.length>0)}function parsePorcelainPaths(output){let entries=parseNulPaths(output),paths=[];for(let index=0;index<entries.length;index++){let entry=entries[index];if(entry.length<4||entry[2]!==" ")return null;let status=entry.slice(0,2),changedPath=entry.slice(3);if(!changedPath)return null;if(paths.push(changedPath),status.includes("R")||status.includes("C")){let originalPath=entries[++index];if(!originalPath)return null;paths.push(originalPath)}}return[...new Set(paths)]}function isSwarmRuntimePath(p){if(p===".swarm")return!0;if(!p.startsWith(".swarm/"))return!1;let dot=p.lastIndexOf("."),extension=dot===-1?"":p.slice(dot).toLowerCase();return!SWARM_VISIBLE_CODE_EXTENSIONS.has(extension)}function filterSwarmRuntimePorcelain(output){let records=output.split("\x00"),kept=[];for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("# ")){kept.push(record2);continue}let primaryPath=null;if(record2.startsWith("? "))primaryPath=record2.slice(2);else if(record2.startsWith("1 "))primaryPath=porcelainV2PathAfterFields(record2,8);else if(record2.startsWith("2 "))primaryPath=porcelainV2PathAfterFields(record2,9);else if(record2.startsWith("u "))primaryPath=porcelainV2PathAfterFields(record2,10);if(primaryPath!==null&&isSwarmRuntimePath(primaryPath)){if(record2.startsWith("2 "))index+=1;continue}if(record2.startsWith("2 ")&&primaryPath!==null){let originalRecord=records[index+1];if(kept.push(record2),typeof originalRecord==="string"&&originalRecord!==""&&isSwarmRuntimePath(originalRecord))kept.push(primaryPath),index+=1;continue}kept.push(record2)}return kept.join("\x00")}function parsePorcelainV2Snapshot(output){let records=output.split("\x00"),headers=[];while(records[0]?.startsWith("# "))headers.push(records.shift());let oidMatch=headers.join(`
550
550
  `).match(/^# branch\.oid (.+)$/m);if(!oidMatch)return null;if(!/^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(oidMatch[1])&&oidMatch[1]!=="(initial)")return null;let gitHead=oidMatch[1]==="(initial)"?null:oidMatch[1],dirtyTrackedPaths=[],untrackedPaths=[],unmergedPaths=[],unmergedCodes=[],dirtySubmodulePaths=[],renameOrCopy=!1;for(let index=0;index<records.length;index++){let record2=records[index];if(!record2)continue;if(record2.startsWith("? ")){untrackedPaths.push(record2.slice(2));continue}if(record2.startsWith("1 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,8);if(!changedPath||!fields[2])return null;if(dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("2 ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,9),originalPath=records[++index];if(!changedPath||!originalPath||!fields[2])return null;if(renameOrCopy=!0,dirtyTrackedPaths.push(changedPath,originalPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}if(record2.startsWith("u ")){let fields=record2.split(" "),changedPath=porcelainV2PathAfterFields(record2,10),unmergedCode=fields[1];if(!changedPath||!fields[2]||!unmergedCode||!/^(?:DD|AU|UD|UA|DU|AA|UU)$/.test(unmergedCode))return null;if(unmergedPaths.push(changedPath),unmergedCodes.push(unmergedCode),dirtyTrackedPaths.push(changedPath),fields[2]!=="N...")dirtySubmodulePaths.push(changedPath);continue}return null}return{gitHead,dirtyTrackedPaths:[...new Set(dirtyTrackedPaths)],untrackedPaths:[...new Set(untrackedPaths)],renameOrCopy,unmergedPaths:[...new Set(unmergedPaths)],unmergedCodes:[...new Set(unmergedCodes)],dirtySubmodulePaths:[...new Set(dirtySubmodulePaths)]}}function porcelainV2PathAfterFields(record2,fields){let offset=0;for(let index=0;index<fields;index++){let delimiter=record2.indexOf(" ",offset);if(delimiter<0)return null;offset=delimiter+1}return record2.slice(offset)||null}function parseCaptureOptions(optionsOrScope,prHeadShaArg){let scope=typeof optionsOrScope==="object"&&optionsOrScope!==null?optionsOrScope.scope??null:optionsOrScope,configuredPrHeadSha=(()=>{if(typeof optionsOrScope!=="object"||optionsOrScope===null)return prHeadShaArg;return optionsOrScope.prHeadSha??null})(),resolveCurrentPrHeadSha=typeof optionsOrScope==="object"&&optionsOrScope!==null&&optionsOrScope.resolveCurrentPrHeadSha===!0;return{scope,configuredPrHeadSha,resolveCurrentPrHeadSha}}function snapshotContentDigest(snapshot){if(snapshot.gitHead===null||snapshot.dirtyHash===null)return null;return digest(`${snapshot.gitHead}
551
551
  ${snapshot.dirtyHash}`)}function captureWorkspaceSnapshot(directory,optionsOrScope=null,prHeadShaArg=null){let{scope,configuredPrHeadSha,resolveCurrentPrHeadSha}=parseCaptureOptions(optionsOrScope,prHeadShaArg),upstreamBefore=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,porcelainRaw=runGit(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),porcelain=porcelainRaw===null?null:filterSwarmRuntimePorcelain(porcelainRaw),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?runGit(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha;return{directory:canonicalRootKey(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]:null,prHeadSha,scope}}async function captureWorkspaceSnapshotAsync(directory,optionsOrScope=null,prHeadShaArg=null){let{scope,configuredPrHeadSha,resolveCurrentPrHeadSha}=parseCaptureOptions(optionsOrScope,prHeadShaArg),upstreamBefore=resolveCurrentPrHeadSha?await runGitAsync(directory,["rev-parse","@{upstream}"]):null,porcelainRaw=await runGitAsync(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),porcelain=porcelainRaw===null?null:filterSwarmRuntimePorcelain(porcelainRaw),snapshot=porcelain===null?null:parsePorcelainV2Snapshot(porcelain),upstreamAfter=resolveCurrentPrHeadSha?await runGitAsync(directory,["rev-parse","@{upstream}"]):null,prHeadSha=resolveCurrentPrHeadSha?upstreamBefore&&upstreamBefore===upstreamAfter?upstreamBefore:null:configuredPrHeadSha,captured={directory:canonicalRootKey(directory),gitHead:snapshot?.gitHead??null,dirtyHash:porcelain===null?null:digest(porcelain),changedFiles:snapshot?[...new Set([...snapshot.dirtyTrackedPaths,...snapshot.untrackedPaths])]:null,prHeadSha,scope},contentDigest=snapshotContentDigest(captured);if(contentDigest!==null&&!shouldSkipSnapshot(directory,contentDigest))try{await atomicWriteSwarmFile(validateSwarmPath(directory,SNAPSHOT_DIGEST_MARKER_FILENAME),`${contentDigest}
552
- `)}catch{}return captured}function shouldSkipSnapshot(directory,digestText2){if(!/^[0-9a-f]{64}$/.test(digestText2))return!1;try{return fs13.readFileSync(validateSwarmPath(directory,SNAPSHOT_DIGEST_MARKER_FILENAME),"utf-8").trim()===digestText2}catch{return!1}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.filter((p)=>!isSwarmRuntimePath(p)).length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))if(!isSwarmRuntimePath(changedPath))changed.add(changedPath)}return[...changed]}async function changedFilesSinceSnapshotAsync(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.filter((p)=>!isSwarmRuntimePath(p)).length>0)return null;let current=await captureWorkspaceSnapshotAsync(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=await runGitAsync(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))if(!isSwarmRuntimePath(changedPath))changed.add(changedPath)}return[...changed]}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(!sameProjectRoot(expected.directory,current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash15("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=33554432,REVISION_MAX_FILES=50000,REVISION_MAX_TOTAL_BYTES=536870912,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,REVISION_ENUMERATION_TIMEOUT_MS=15000,GITLINK_MODE_PATTERN,SWARM_VISIBLE_CODE_EXTENSIONS,SNAPSHOT_DIGEST_MARKER_FILENAME="workspace-snapshot.digest",compareWorkspaceSnapshot,_internals30;var init_workspace_snapshot=__esm(()=>{init_utils2();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;SWARM_VISIBLE_CODE_EXTENSIONS=new Set([".js",".jsx",".mjs",".cjs",".ts",".tsx",".py",".pyw",".go",".rs",".php",".pl",".java",".kt",".swift",".scala",".c",".h",".cpp",".cs",".rb",".lua",".r",".sh",".bash",".zsh",".ps1",".psm1",".bat",".cmd",".vb",".fs"]);compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals30={spawnSync:child_process.spawnSync,bunSpawn,resolveGitExecutable,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve17)=>setImmediate(resolve17)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs13.readFileSync(filePath)}});import*as fs14 from"node:fs";import*as path28 from"node:path";function authorityKeyFor(event){switch(event.type){case AUTHORITY_RETRY:{if(typeof event.taskId==="string"&&typeof event.retryEpoch==="number"&&Number.isFinite(event.retryEpoch)&&typeof event.action==="string"&&RETRY_ACTIONS.has(event.action))return`retry|${event.taskId}|${event.retryEpoch}|${event.action}`;return null}case AUTHORITY_REPAIR:{if(typeof event.taskId==="string"&&typeof event.transitionId==="string")return`repair|${event.taskId}|${event.transitionId}`;return null}case AUTHORITY_DRIFT_ACK:case AUTHORITY_DRIFT_REPAIR:{if(typeof event.transitionId==="string")return`drift|${String(event.type)}|${event.transitionId}`;return null}default:{if(PUBLICATION_LIVE_EVENT_TYPES.has(String(event.type))||PUBLICATION_TERMINAL_EVENT_TYPES.has(String(event.type))){if(typeof event.sessionID==="string"&&typeof event.generation==="number"&&Number.isFinite(event.generation))return`pr_feedback_publication|${event.sessionID}|${event.generation}`}return null}}}function emptyFolded(){return{totalEvents:0,byType:{},corrupt:0,dropped:0,oldestTimestamp:null,newestTimestamp:null}}function emptyManifest(){return{v:1,type:MANIFEST_TYPE,schemaVersion:MANIFEST_SCHEMA,folded:emptyFolded(),updatedAt:new Date().toISOString()}}function parseManifestLine(line){let trimmed=line.trim();if(!trimmed)return null;try{let obj=JSON.parse(trimmed);if(typeof obj!=="object"||obj===null)return null;let rec=obj;if(rec.type!==MANIFEST_TYPE||rec.v!==1||rec.schemaVersion!==MANIFEST_SCHEMA||typeof rec.folded!=="object"||rec.folded===null)return null;let f=rec.folded,manifest=emptyManifest(),num=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0?v:0;if(manifest.folded.totalEvents=num(f.totalEvents),manifest.folded.corrupt=num(f.corrupt),manifest.folded.dropped=num(f.dropped),typeof f.byType==="object"&&f.byType!==null){for(let[k,v]of Object.entries(f.byType))if(typeof v==="number"&&Number.isFinite(v)&&v>=0)manifest.folded.byType[k]=v}if(typeof f.oldestTimestamp==="string")manifest.folded.oldestTimestamp=f.oldestTimestamp;if(typeof f.newestTimestamp==="string")manifest.folded.newestTimestamp=f.newestTimestamp;return manifest.updatedAt=typeof rec.updatedAt==="string"?rec.updatedAt:new Date().toISOString(),manifest}catch{return null}}function coreEventsFilePath(directory){return path28.join(directory,".swarm","events.jsonl")}function lockFilePath(directory){return path28.join(directory,".swarm","events.lock")}function authorityIndexPath(directory){return path28.join(directory,".swarm","events-authority-index.json")}function tmpPathFor(finalPath){return`${finalPath}.${process.pid}.tmp`}function readBoundedChunk(filePath,maxBytes,offset=0){try{if(!_internals31.existsSync(filePath))return{text:"",truncated:!1};let fd=_internals31.openSync(filePath,"r");try{let size=_internals31.statSync(filePath).size,readable=Math.max(0,size-offset),truncated=readable>maxBytes,len=Math.min(readable,maxBytes),buf=Buffer.alloc(len),read=0;while(read<len){let n=_internals31.readSync(fd,buf,read,len-read,offset+read);if(n<=0)break;read+=n}return{text:buf.toString("utf-8",0,read),truncated}}finally{_internals31.closeSync(fd)}}catch{return warnThrottled("bounded read failed (transient I/O)"),{text:"",truncated:!1}}}function fileSizeOrZero(filePath){try{if(!_internals31.existsSync(filePath))return 0;return _internals31.statSync(filePath).size}catch{return 0}}function fileEndsWithNewline(filePath){try{if(!_internals31.existsSync(filePath))return!0;let size=_internals31.statSync(filePath).size;if(size===0)return!0;let fd=_internals31.openSync(filePath,"r");try{let buf=Buffer.alloc(1);return _internals31.readSync(fd,buf,0,1,size-1)<=0||buf[0]===10}finally{_internals31.closeSync(fd)}}catch{return!0}}function eventDiscriminator(event){if(typeof event.type==="string"&&event.type.length>0)return event.type.slice(0,64);if(typeof event.event==="string"&&event.event.length>0)return event.event.slice(0,64);return"__untyped__"}function eventTimestamp(event){if(typeof event.timestamp!=="string")return null;let ts=Date.parse(event.timestamp);return Number.isNaN(ts)?null:event.timestamp}function foldLineInto(folded,event){folded.totalEvents+=1;let key=eventDiscriminator(event),keys=Object.keys(folded.byType);if(folded.byType[key]!==void 0||keys.length<BY_TYPE_MAX_KEYS)folded.byType[key]=(folded.byType[key]??0)+1;else folded.byType[BY_TYPE_OTHER]=(folded.byType[BY_TYPE_OTHER]??0)+1;let ts=eventTimestamp(event);if(ts!==null){if(folded.oldestTimestamp===null||ts<folded.oldestTimestamp)folded.oldestTimestamp=ts;if(folded.newestTimestamp===null||ts>folded.newestTimestamp)folded.newestTimestamp=ts}}function cloneFolded(folded){return{totalEvents:folded.totalEvents,byType:{...folded.byType},corrupt:folded.corrupt,dropped:folded.dropped,oldestTimestamp:folded.oldestTimestamp,newestTimestamp:folded.newestTimestamp}}function emptyAuthorityIndex(){return{version:1,entries:{},evicted:0}}function loadAuthorityIndex(directory){let indexPath=authorityIndexPath(directory);try{if(!_internals31.existsSync(indexPath))return{kind:"absent"};let raw=_internals31.readFileSync(indexPath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.version!==1||typeof parsed.entries!=="object"||parsed.entries===null)return{kind:"corrupt"};let entries={};for(let[k,v]of Object.entries(parsed.entries))if(typeof v==="string")entries[k]=v;let evictedRaw=parsed.evicted;return{kind:"ok",index:{version:1,entries,evicted:typeof evictedRaw==="number"&&Number.isFinite(evictedRaw)&&evictedRaw>=0?evictedRaw:0}}}catch{return{kind:"corrupt"}}}function mergeAuthorityKeys(directory,state2,keys){if(keys.length===0)return;let base=state2.kind==="ok"?{version:1,entries:{...state2.index.entries},evicted:state2.index.evicted}:emptyAuthorityIndex(),now=new Date().toISOString();for(let key of keys)base.entries[key]=now;let limit=_internals31.limits.authorityIndexMaxEntries,allKeys=Object.keys(base.entries);if(allKeys.length>limit){allKeys.sort((a,b)=>base.entries[a]<=base.entries[b]?-1:1);let excess=allKeys.length-limit;for(let i=0;i<excess;i+=1)delete base.entries[allKeys[i]];base.evicted+=excess}authorityIndexAtomicReplace(directory,base)}function authorityIndexAtomicReplace(directory,index){let finalPath=authorityIndexPath(directory),tmpPath=tmpPathFor(finalPath);try{if(_internals31.existsSync(tmpPath))try{_internals31.unlinkSync(tmpPath)}catch{}_internals31.writeFileSync(tmpPath,`${JSON.stringify(index)}
552
+ `)}catch{}return captured}function shouldSkipSnapshot(directory,digestText2){if(!/^[0-9a-f]{64}$/.test(digestText2))return!1;try{return fs13.readFileSync(validateSwarmPath(directory,SNAPSHOT_DIGEST_MARKER_FILENAME),"utf-8").trim()===digestText2}catch{return!1}}function changedFilesSinceSnapshot(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.filter((p)=>!isSwarmRuntimePath(p)).length>0)return null;let current=captureWorkspaceSnapshot(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=runGit(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))if(!isSwarmRuntimePath(changedPath))changed.add(changedPath)}return[...changed]}async function changedFilesSinceSnapshotAsync(directory,baseline){if(!baseline?.gitHead||baseline.changedFiles==null)return null;if(baseline.changedFiles.filter((p)=>!isSwarmRuntimePath(p)).length>0)return null;let current=await captureWorkspaceSnapshotAsync(directory);if(!current.gitHead||current.changedFiles==null)return null;let changed=new Set(current.changedFiles);if(baseline.gitHead!==current.gitHead){let committed=await runGitAsync(directory,["diff","--name-only","-z",baseline.gitHead,current.gitHead]);if(committed===null)return null;for(let changedPath of parseNulPaths(committed))if(!isSwarmRuntimePath(changedPath))changed.add(changedPath)}return[...changed]}function committedFilesBetween(directory,fromHead,toHead){if(fromHead===null||toHead===null)return null;if(fromHead===toHead)return[];let committed=runGit(directory,["diff","--name-only","--no-renames","-z",fromHead,toHead]);if(committed===null)return null;return parseNulPaths(committed)}function workspaceSnapshotMatches(expected,current){if(!expected)return{ok:!0};if(!sameProjectRoot(expected.directory,current.directory))return{ok:!1,reason:`directory changed: expected ${expected.directory}, got ${current.directory}`};let checks3=["gitHead","dirtyHash","prHeadSha"];for(let key of checks3){let expectedValue=expected[key];if(expectedValue===null)continue;if(current[key]!==expectedValue)return{ok:!1,reason:`${key} changed: expected ${expectedValue}, got ${current[key]??"unknown"}`}}return{ok:!0}}function compareWorkspaceSnapshots(expected,current){let result=workspaceSnapshotMatches(expected,current);if(result.ok)return{stale:!1};return{stale:!0,reason:result.reason}}function digest(text){return createHash15("sha256").update(text).digest("hex")}var GIT_SNAPSHOT_TIMEOUT_MS=3000,GIT_SNAPSHOT_MAX_BUFFER=33554432,REVISION_MAX_FILES=50000,REVISION_MAX_TOTAL_BYTES=536870912,REVISION_READ_CHUNK_BYTES=65536,REVISION_YIELD_EVERY_CHUNKS=16,REVISION_ENUMERATION_TIMEOUT_MS=15000,GITLINK_MODE_PATTERN,SWARM_VISIBLE_CODE_EXTENSIONS,SNAPSHOT_DIGEST_MARKER_FILENAME="workspace-snapshot.digest",compareWorkspaceSnapshot,_internals30;var init_workspace_snapshot=__esm(()=>{init_utils2();init_atomic_write();init_bun_compat();init_canonical_root();init_git_executable();GITLINK_MODE_PATTERN=/^:\d{6} 160000 |^:160000 \d{6} /;SWARM_VISIBLE_CODE_EXTENSIONS=new Set([".js",".jsx",".mjs",".cjs",".ts",".tsx",".py",".pyw",".go",".rs",".php",".pl",".java",".kt",".swift",".scala",".c",".h",".cpp",".cs",".rb",".lua",".r",".sh",".bash",".zsh",".ps1",".psm1",".bat",".cmd",".vb",".fs"]);compareWorkspaceSnapshot=workspaceSnapshotMatches;_internals30={spawnSync:child_process.spawnSync,bunSpawn,resolveGitExecutable,gitTimeoutMs:GIT_SNAPSHOT_TIMEOUT_MS,yieldControl:()=>new Promise((resolve17)=>setImmediate(resolve17)),parsePorcelainV2Snapshot,revisionMaxFiles:REVISION_MAX_FILES,revisionMaxTotalBytes:REVISION_MAX_TOTAL_BYTES,gitSnapshotMaxBuffer:GIT_SNAPSHOT_MAX_BUFFER,revisionEnumerationTimeoutMs:REVISION_ENUMERATION_TIMEOUT_MS,readChangedFileSync:(filePath)=>fs13.readFileSync(filePath)}});import*as fs14 from"node:fs";import*as path28 from"node:path";function authorityKeyFor(event){switch(event.type){case AUTHORITY_RETRY:{if(typeof event.taskId==="string"&&typeof event.retryEpoch==="number"&&Number.isFinite(event.retryEpoch)&&typeof event.action==="string"&&RETRY_ACTIONS.has(event.action))return`retry|${event.taskId}|${event.retryEpoch}|${event.action}`;return null}case AUTHORITY_REPAIR:{if(typeof event.taskId==="string"&&typeof event.transitionId==="string")return`repair|${event.taskId}|${event.transitionId}`;return null}case AUTHORITY_DRIFT_ACK:case AUTHORITY_DRIFT_REPAIR:{if(typeof event.transitionId==="string")return`drift|${String(event.type)}|${event.transitionId}`;return null}default:{if(PUBLICATION_LIVE_EVENT_TYPES.has(String(event.type))||PUBLICATION_TERMINAL_EVENT_TYPES.has(String(event.type))){if(typeof event.sessionID==="string"&&typeof event.generation==="number"&&Number.isFinite(event.generation))return`pr_feedback_publication|${event.sessionID}|${event.generation}`}return null}}}function emptyFolded(){return{totalEvents:0,byType:{},corrupt:0,dropped:0,oldestTimestamp:null,newestTimestamp:null}}function emptyManifest(){return{v:1,type:MANIFEST_TYPE,schemaVersion:MANIFEST_SCHEMA,folded:emptyFolded(),updatedAt:new Date().toISOString()}}function parseManifestLine(line){let trimmed=line.trim();if(!trimmed)return null;try{let obj=JSON.parse(trimmed);if(typeof obj!=="object"||obj===null)return null;let rec=obj;if(rec.type!==MANIFEST_TYPE||rec.v!==1||rec.schemaVersion!==MANIFEST_SCHEMA||typeof rec.folded!=="object"||rec.folded===null)return null;let f=rec.folded,manifest=emptyManifest(),num=(v)=>typeof v==="number"&&Number.isFinite(v)&&v>=0?v:0;if(manifest.folded.totalEvents=num(f.totalEvents),manifest.folded.corrupt=num(f.corrupt),manifest.folded.dropped=num(f.dropped),typeof f.byType==="object"&&f.byType!==null){for(let[k,v]of Object.entries(f.byType))if(typeof v==="number"&&Number.isFinite(v)&&v>=0)manifest.folded.byType[k]=v}if(typeof f.oldestTimestamp==="string")manifest.folded.oldestTimestamp=f.oldestTimestamp;if(typeof f.newestTimestamp==="string")manifest.folded.newestTimestamp=f.newestTimestamp;return manifest.updatedAt=typeof rec.updatedAt==="string"?rec.updatedAt:new Date().toISOString(),manifest}catch{return null}}function coreEventsFilePath(directory){return path28.join(directory,".swarm","events.jsonl")}function lockFilePath(directory){return path28.join(directory,".swarm","events.lock")}function authorityIndexPath(directory){return path28.join(directory,".swarm","events-authority-index.json")}function tmpPathFor(finalPath){return`${finalPath}.${process.pid}.tmp`}function readBoundedChunk(filePath,maxBytes,offset=0){try{if(!_internals31.existsSync(filePath))return{text:"",truncated:!1};let fd=_internals31.openSync(filePath,"r");try{let size=_internals31.statSync(filePath).size,readable=Math.max(0,size-offset),truncated=readable>maxBytes,len=Math.min(readable,maxBytes),buf=Buffer.alloc(len),read=0;while(read<len){let n=_internals31.readSync(fd,buf,read,len-read,offset+read);if(n<=0)break;read+=n}return{text:buf.toString("utf-8",0,read),truncated}}finally{_internals31.closeSync(fd)}}catch{return warnThrottled("bounded read failed (transient I/O)"),{text:"",truncated:!1}}}function fileSizeOrZero(filePath){try{if(!_internals31.existsSync(filePath))return 0;return _internals31.statSync(filePath).size}catch{return 0}}function fileEndsWithNewline(filePath){try{if(!_internals31.existsSync(filePath))return!0;let size=_internals31.statSync(filePath).size;if(size===0)return!0;let fd=_internals31.openSync(filePath,"r");try{let buf=Buffer.alloc(1);return _internals31.readSync(fd,buf,0,1,size-1)<=0||buf[0]===10}finally{_internals31.closeSync(fd)}}catch{return!0}}function eventDiscriminator(event){if(typeof event.type==="string"&&event.type.length>0)return event.type.slice(0,64);if(typeof event.event==="string"&&event.event.length>0)return event.event.slice(0,64);return"__untyped__"}function eventTimestamp(event){if(typeof event.timestamp!=="string")return null;let ts=Date.parse(event.timestamp);return Number.isNaN(ts)?null:event.timestamp}function foldLineInto(folded,event){folded.totalEvents+=1;let key=eventDiscriminator(event),keys=Object.keys(folded.byType);if(folded.byType[key]!==void 0||keys.length<BY_TYPE_MAX_KEYS)folded.byType[key]=(folded.byType[key]??0)+1;else folded.byType[BY_TYPE_OTHER]=(folded.byType[BY_TYPE_OTHER]??0)+1;let ts=eventTimestamp(event);if(ts!==null){if(folded.oldestTimestamp===null||ts<folded.oldestTimestamp)folded.oldestTimestamp=ts;if(folded.newestTimestamp===null||ts>folded.newestTimestamp)folded.newestTimestamp=ts}}function cloneFolded(folded){return{totalEvents:folded.totalEvents,byType:{...folded.byType},corrupt:folded.corrupt,dropped:folded.dropped,oldestTimestamp:folded.oldestTimestamp,newestTimestamp:folded.newestTimestamp}}function emptyAuthorityIndex(){return{version:1,entries:{},evicted:0}}function loadAuthorityIndex(directory){let indexPath=authorityIndexPath(directory);try{if(!_internals31.existsSync(indexPath))return{kind:"absent"};let raw=_internals31.readFileSync(indexPath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.version!==1||typeof parsed.entries!=="object"||parsed.entries===null)return{kind:"corrupt"};let entries={};for(let[k,v]of Object.entries(parsed.entries))if(typeof v==="string")entries[k]=v;let evictedRaw=parsed.evicted;return{kind:"ok",index:{version:1,entries,evicted:typeof evictedRaw==="number"&&Number.isFinite(evictedRaw)&&evictedRaw>=0?evictedRaw:0}}}catch{return{kind:"corrupt"}}}function mergeAuthorityKeys(directory,state2,keys){if(keys.length===0)return;let base=state2.kind==="ok"?{version:1,entries:{...state2.index.entries},evicted:state2.index.evicted}:emptyAuthorityIndex(),now=new Date().toISOString();for(let key of keys)base.entries[key]=now;let limit=_internals31.limits.authorityIndexMaxEntries,allKeys=Object.keys(base.entries);if(allKeys.length>limit){allKeys.sort((a,b)=>base.entries[a]<=base.entries[b]?-1:1);let excess=allKeys.length-limit;for(let i=0;i<excess;i+=1)delete base.entries[allKeys[i]];base.evicted+=excess}authorityIndexAtomicReplace(directory,base)}function authorityIndexAtomicReplace(directory,index){let finalPath=authorityIndexPath(directory),tmpPath=tmpPathFor(finalPath);try{if(_internals31.existsSync(tmpPath))try{_internals31.unlinkSync(tmpPath)}catch{}_internals31.writeFileSync(tmpPath,`${JSON.stringify(index)}
553
553
  `,"utf-8"),renameSyncWithRetry(tmpPath,finalPath)}catch{try{if(_internals31.existsSync(tmpPath))_internals31.unlinkSync(tmpPath)}catch{}throw Error("core-events authority index atomic replace failed")}}function atomicReplace(directory,content){let lines=content.split(`
554
554
  `);if(lines.length<2||lines[lines.length-1]!=="")throw Error("core-events atomic replace failed (framing)");if(parseManifestLine(lines[0]??"")===null)throw Error("core-events atomic replace failed (manifest)");for(let i=1;i<lines.length-1;i+=1){let line=lines[i];if(line.trim()==="")continue;JSON.parse(line)}let finalPath=coreEventsFilePath(directory),tmpPath=tmpPathFor(finalPath);try{if(_internals31.existsSync(tmpPath))try{_internals31.unlinkSync(tmpPath)}catch{}if(_internals31.writeFileSync(tmpPath,content,"utf-8"),_internals31.readFileSync(tmpPath,"utf-8")!==content)throw Error("tmp verify mismatch");renameSyncWithRetry(tmpPath,finalPath)}catch{try{if(_internals31.existsSync(tmpPath))_internals31.unlinkSync(tmpPath)}catch{}throw Error("core-events atomic replace failed")}}function syncSleep2(ms){try{Atomics.wait(sleepScratch,0,0,ms)}catch{let start=_internals31.now();while(_internals31.now()-start<ms);}}function renameSyncWithRetry(fromPath,toPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS2.length;attempt+=1)try{_internals31.renameSync(fromPath,toPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES2.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS2.length)syncSleep2(RENAME_RETRY_DELAYS_MS2[attempt])}throw lastError}function tryLockOnce(directory){let lockPath=lockFilePath(directory);try{_internals31.mkdirSync(path28.dirname(lockPath),{recursive:!0});let fd=_internals31.openSync(lockPath,"wx");return _internals31.closeSync(fd),!0}catch{try{if(_internals31.now()-_internals31.statSync(lockPath).mtimeMs>LOCK_STALE_MS){try{_internals31.unlinkSync(lockPath)}catch{}try{let fd=_internals31.openSync(lockPath,"wx");return _internals31.closeSync(fd),!0}catch{return!1}}}catch{}return!1}}function withCoreEventStoreLock(directory,fn2){for(let attempt=0;attempt<LOCK_RETRY_ATTEMPTS;attempt+=1){if(tryLockOnce(directory))try{return fn2()}finally{try{_internals31.unlinkSync(lockFilePath(directory))}catch{}}if(attempt<LOCK_RETRY_ATTEMPTS-1)syncSleep2(LOCK_RETRY_DELAY_MS)}return null}function shouldRunMaintenance(linesAppended=1){if(_appendCount+=linesAppended,_appendCount>=_internals31.limits.checkInterval)return _appendCount=0,!0;return!1}function warnThrottled(message){let now=_internals31.now();if(now-_lastWarnAt<_internals31.limits.warnCooldownMs)return;_lastWarnAt=now,warn(`core-events: ${message}`)}function readStoreFull(directory){let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return{manifest:null,lines:[],corruptLines:0};let text;try{text=_internals31.readFileSync(filePath,"utf-8")}catch{return{manifest:null,lines:[],corruptLines:0}}let rawLines=text.split(`
555
555
  `),lines=[],corruptLines=0,manifest=null;for(let i=0;i<rawLines.length;i+=1){let line=rawLines[i];if(line.trim()==="")continue;if(i===0){if(manifest=parseManifestLine(line),manifest)continue}try{let parsed=JSON.parse(line);if(typeof parsed==="object"&&parsed!==null&&!Array.isArray(parsed))lines.push({line,event:parsed});else corruptLines+=1}catch{corruptLines+=1}}return{manifest,lines,corruptLines}}function coverageFor(fileExists,lineCount,truncated){if(!fileExists||lineCount===0)return"empty";return truncated?"truncated":"complete"}function readCoreEvents(directory){let filePath=coreEventsFilePath(directory);if(!_internals31.existsSync(filePath))return{text:"",truncated:!1,coverage:"empty"};let size=fileSizeOrZero(filePath),truncated=size>_internals31.limits.readMaxBytes,offset=truncated?Math.max(0,size-_internals31.limits.readMaxBytes):0,text=readBoundedChunk(filePath,_internals31.limits.readMaxBytes,offset).text;if(truncated){let firstNewline=text.indexOf(`
@@ -1278,7 +1278,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1278
1278
  `,"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(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")throw error49;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 ${path99.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(error49){if(error49.code!=="ENOENT")throw error49}}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(error49){if(error49.code==="ENOENT")return null;throw error49}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&&currentRevision!==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(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve51)=>{timeout=setTimeout(()=>{resolve51({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((resolve51)=>{release=resolve51}),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(error49){if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(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(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_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(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await hooks.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await hooks.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,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((resolve51)=>{release=resolve51}),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(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(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(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp5.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}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,codec2,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 path100 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=path100.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(error49){if(error49.code==="ENOENT")return null;throw error49}let decoded=JSON.parse(raw),parsed=AuthorizationFileSchema.safeParse(decoded);if(!parsed.success)throw Error(`reentry authorization store is invalid: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.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<=_internals92.renameRetryDelaysMs.length;attempt++)try{await _internals92.renameImpl(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES4.has(code))throw err;if(attempt<_internals92.renameRetryDelaysMs.length)await new Promise((resolve51)=>setTimeout(resolve51,_internals92.renameRetryDelaysMs[attempt]))}throw lastError}async function writeAuthorizationFile(filePath,file2){let serialized2=serializeAuthorizationFile(file2);if(Buffer.byteLength(serialized2,"utf8")>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store exceeds its write bound");await fsp6.mkdir(path100.dirname(filePath),{recursive:!0});let tempPath=path100.join(path100.dirname(filePath),`.${path100.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(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeAuthorizationFile(file2){return`${JSON.stringify(file2,null,2)}
1279
1279
  `}async function readTextFileIfExists2(filePath){try{return await fsp6.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker2(filePath){await fsp6.mkdir(path100.dirname(filePath),{recursive:!0}),await fsp6.writeFile(filePath,`sqlite-projection
1280
1280
  `,"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 ${path100.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(error49){if(error49.code==="ENOENT")return null;throw error49}let legacy=await readAuthorizationFile(filePath);if(!legacy)return null;let outcome=importCoordinationOnce(directory,{source:path100.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((record2)=>Date.parse(record2.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((record2)=>!record2.consumedAt).sort(newest),consumed=unexpired.filter((record2)=>Boolean(record2.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((record3)=>!record3.consumedAt&&record3.role===request.role&&record3.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((record3)=>!record3.consumedAt).length>=MAX_ACTIVE_AUTHORIZATIONS)throw Error(`BLOCKED: re-entry authorization store is at its bound of ${MAX_ACTIVE_AUTHORIZATIONS} active authorizations`);let record2={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:[record2,...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}),record2}throw Error("BLOCKED: re-entry authorization store changed concurrently; reload the active session state before retrying")})}function authorizationMatchesBinding(record2,binding){return binding.prHeadSha===record2.prHeadSha&&binding.revisionDigest===record2.revisionDigest&&binding.generation===record2.generation&&binding.workflowInstanceId===record2.workflowInstanceId&&binding.runId===record2.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((record2)=>!record2.consumedAt&&record2.role===request.role&&record2.sessionId===trimmedSession&&authorizationMatchesBinding(record2,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((record2)=>record2.consumedCallId===request.callID&&record2.role===request.role&&record2.sessionId===trimmedSession&&Date.parse(record2.expiresAt)>nowMs3),index=sameCallIndex>=0?sameCallIndex:records.findIndex((record2)=>!record2.consumedAt&&record2.role===request.role&&record2.sessionId===trimmedSession&&Date.parse(record2.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,_internals92;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"]);_internals92={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(record2){if(!CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record2.status))return null;let result=record2.terminalResult?.result??record2.result,providerClass=result?.terminalErrorClass?.category;if(result?.terminalErrorClass&&providerClass){if(record2.status!=="error")return{kind:"ignored",reason:"cancellation"};if(result.terminalErrorClass.kind==="provider")return{kind:"provider_terminal",providerClass,batchId:record2.batchId??"",laneId:record2.laneId??"",terminalAtMs:record2.terminalResult?.recordedAt??record2.completedAt??record2.updatedAt??record2.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(record2.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),hash3="";try{let h=2166136261;for(let index=0;index<body.length;index+=1)h^=body.charCodeAt(index),h=Math.imul(h,16777619);hash3=(h>>>0).toString(16).padStart(8,"0")}catch{hash3="unserializable"}return{kind:"malformed",diagnostic:{code:"malformed_circuit_dropped",bodyHash8:hash3,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 record2=current??freshRecord(input.nowMs,!1);if(record2.state==="CLOSED"){let evidence2=scanPrReviewCircuitEvidence(input.laneSignals,record2.generation,record2.evidenceWaterline?Date.parse(record2.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:{...record2,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(record2.state==="OPEN"){let openUntilMs=record2.openUntil?Date.parse(record2.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:{...record2,state:"HALF_OPEN",probe:{batchId:input.admission.batchId,laneId:input.admission.laneId,admittedAt:new Date(input.nowMs).toISOString()}}}}let probe2=record2.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=[...record2.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:{...record2,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:record2.generation+1,contributors:[],evidenceWaterline:new Date(input.probeObservation.terminalAtMs||input.nowMs).toISOString()}};return{action:"block",reason:"circuit_open",changed:!0,record:{...record2,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 fs64 from"node:fs/promises";import*as path101 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 intersection2=0;for(let token of a)if(b.has(token))intersection2+=1;return intersection2/(a.size+b.size-intersection2)}function normalizedLocation(location){let file2=location.file.replaceAll("\\","/").trim().toLocaleLowerCase("en-US"),line=Number(location.line),lineEnd=location.lineEnd===void 0?line:Number(location.lineEnd);return`${file2}:${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(",")}`,hash3=2166136261;for(let char of material)hash3^=char.charCodeAt(0),hash3=Math.imul(hash3,16777619);return`finding-${(hash3>>>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"&&currentAction!=="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((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.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=path101.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 fs64.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(error49){if(error49.code!=="ENOENT")throw error49}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,path101.join("pr-review",taskId,"finding-policy.json")),evidence2=JSON.parse(await fs64.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(`
1281
- `).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 readFileSync39}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path102 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(record2){if("missingDimension"in record2)return{schemaVersion:2,runId:record2.runId,prHeadSha:record2.prHeadSha,revisionDigest:record2.revisionDigest,unresolvedDimensions:[{dimension:record2.missingDimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:record2.failureClass,terminalEventId:record2.terminalEventId,safeDetail:PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[record2.failureClass]}],admittedAt:record2.admittedAt};return record2}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((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.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 record2 of batchRead.value.filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record2.terminalResult,eventlessFailure=!terminal&&CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record2.status),result=terminal?.result??record2.result,failureClass=result?.workflowLaneFailureClass;if(!terminal&&!eventlessFailure||!failureClass)continue;if((terminal?.status??record2.status)==="completed")continue;let candidate={failureClass,terminalEventId:terminal?terminal.eventId:`eventless:${record2.status}:${result?.digest??""}`,recordedAt:terminal?terminal.recordedAt:record2.completedAt??record2.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 record2 of records.filter((candidate)=>candidate.laneId===lane.laneId)){let result=record2.result;if(!result)continue;let structured=validateExactStructuredReceiptCoverage({record:record2,result,artifact:null,expected:{mode:"swarm-pr-review:base",workflowLane:lane.workflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:record2.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:record2.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 path102.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((record2)=>record2.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:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state2;if(!record2&&!relativePath&&!expectedDigest)return null;if(!record2||!relativePath||!expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure state is incomplete");let expectedPath=coverageDisclosureRelativePath(record2.runId).split(path102.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(record2))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 record2={schemaVersion:2,runId:normalizedRunId,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path102.sep).join("/"),absolutePath=validateSwarmPath(directory,relativePath),raw=JSON.stringify(record2,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(readFileSync39(absolutePath,"utf8")!==raw)throw Error("BLOCKED: partial base coverage disclosure path already contains different content")}catch(error49){if(error49.code==="ENOENT"){disclosureWasMissing=!0;try{await writeAtomicJson2(directory,absolutePath,record2)}catch(writeError){throw await removeNewDisclosure(),writeError}}else throw error49}let digest3=createHash51("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:digest3})}catch(error49){throw await removeNewDisclosure(),error49}})}async function rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,options){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record2=state2?.prReviewPartialBaseCoverage;if(!state2||!record2||record2.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(error49){if(error49.code!=="ENOENT")throw error49}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,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state2,record2,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&&current&&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 record2=batchRead.value.find((candidate)=>candidate.laneId===laneId),ref=record2?.result?.outputRef?.trim()??record2?.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 record2 of state2.prFeedbackVerifications??[])for(let ownership of record2.ownership){let batchRead=findByBatchIdDetailed(directory,record2.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 ${record2.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 record2={batchId:event.batchId,lanes:event.lanes,validatedAt:event.validatedAt},nextDispatches=[...dispatches,record2];return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record2},[{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 readFileSync40,statSync as statSync38}from"node:fs";import*as fsp8 from"node:fs/promises";import*as path103 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:[path103.join(".swarm",workflowCheckoutMutationLockRelativePath()),path103.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(record2){if(record2.status!=="cancelled"&&record2.status!=="stale"&&record2.status!=="error")return!1;return record2.terminalResult?.result.workflowLaneFailureClass==="liveness"||record2.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((record3)=>record3.subagentSessionId===child&&record3.correlationId===child&&(record3.mode==="swarm-pr-review:base"||record3.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,record2=repairRecord??preliminary[0],childOfRecord=record2.subagentSessionId;if(!record2.batchId||!record2.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record2.batchId||input.laneId!==void 0&&input.laneId!==record2.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record2;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(record2.jobId),dispatchWorkflowRevision=record2.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(record2.mode!=="swarm-pr-review:base"&&record2.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record2.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:[];if(!record2.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record2.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:record2.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record2.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record2.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record2.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(error49){if(error49.code==="ENOENT")return;throw error49}let entriesRead=0,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES)throw Error("BLOCKED: PR workflow gate inventory exceeds the bounded checkout-restoration scan; clear stale workflow state before retrying");if(!/\.json$/i.test(entry.name))continue;if(!entry.isFile())throw Error("BLOCKED: PR workflow gate inventory contains a non-regular state entry; checkout restoration cannot prove project inactivity");let statePath2=validateSwarmPath(directory,path103.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path103.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(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,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(error49){return{statuses:new Map,degradedReason:error49===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 record2 of records){let subagentSessionId=record2.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=(record2,reason)=>({laneId:record2.laneId??record2.correlationId,pendingMs:Math.max(0,now-record2.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record2)=>(record2.status==="pending"||record2.status==="running"||record2.status==="ingesting")&&now-record2.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((record2)=>degraded(record2,"probe-timeout"));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record2 of pastThreshold){let pendingMs=now-record2.updatedAt,laneId=record2.laneId??record2.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record2.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((record2)=>degraded(record2,"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(record2){return record2.laneId??record2.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record2,sessionID){return record2.parentSessionId===sessionID&&record2.mode?.startsWith("swarm-pr-")===!0&&(record2.status==="pending"||record2.status==="running")}async function abortLaneSessionForWatchdog(record2){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record2.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record2.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(`
1281
+ `).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 readFileSync39}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path102 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(record2){if("missingDimension"in record2)return{schemaVersion:2,runId:record2.runId,prHeadSha:record2.prHeadSha,revisionDigest:record2.revisionDigest,unresolvedDimensions:[{dimension:record2.missingDimension,terminalState:"FAILED",reasonKind:"lane_failure",failureClass:record2.failureClass,terminalEventId:record2.terminalEventId,safeDetail:PR_REVIEW_FAILURE_CLASS_SAFE_DETAILS[record2.failureClass]}],admittedAt:record2.admittedAt};return record2}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((record2)=>record2.laneId===lane.laneId);if(laneRecords.length===0)continue;if(!laneRecords.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES.has(record2.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 record2 of batchRead.value.filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record2.terminalResult,eventlessFailure=!terminal&&CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record2.status),result=terminal?.result??record2.result,failureClass=result?.workflowLaneFailureClass;if(!terminal&&!eventlessFailure||!failureClass)continue;if((terminal?.status??record2.status)==="completed")continue;let candidate={failureClass,terminalEventId:terminal?terminal.eventId:`eventless:${record2.status}:${result?.digest??""}`,recordedAt:terminal?terminal.recordedAt:record2.completedAt??record2.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 record2 of records.filter((candidate)=>candidate.laneId===lane.laneId)){let result=record2.result;if(!result)continue;let structured=validateExactStructuredReceiptCoverage({record:record2,result,artifact:null,expected:{mode:"swarm-pr-review:base",workflowLane:lane.workflowLane,ownedWorkflowLanes,prHeadSha:state2.prHeadSha??"",gitHead:state2.prHeadSha??"",revisionDigest,workflowInstanceId:state2.workflowInstanceId,workflowRevision:record2.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:record2.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 path102.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((record2)=>record2.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:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state2;if(!record2&&!relativePath&&!expectedDigest)return null;if(!record2||!relativePath||!expectedDigest)throw Error("BLOCKED: PR_REVIEW partial base coverage disclosure state is incomplete");let expectedPath=coverageDisclosureRelativePath(record2.runId).split(path102.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(record2))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 record2={schemaVersion:2,runId:normalizedRunId,prHeadSha:state2.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path102.sep).join("/"),absolutePath=validateSwarmPath(directory,relativePath),raw=JSON.stringify(record2,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(readFileSync39(absolutePath,"utf8")!==raw)throw Error("BLOCKED: partial base coverage disclosure path already contains different content")}catch(error49){if(error49.code==="ENOENT"){disclosureWasMissing=!0;try{await writeAtomicJson2(directory,absolutePath,record2)}catch(writeError){throw await removeNewDisclosure(),writeError}}else throw error49}let digest3=createHash51("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state2,updatedAt:isoNow(),prReviewPartialBaseCoverage:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:digest3})}catch(error49){throw await removeNewDisclosure(),error49}})}async function rollbackPrReviewPartialBaseCoverageAdmission(directory,sessionID,options){return withSessionStateMutation(directory,sessionID.trim(),async()=>{let state2=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record2=state2?.prReviewPartialBaseCoverage;if(!state2||!record2||record2.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(error49){if(error49.code!=="ENOENT")throw error49}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,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state2,record2,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&&current&&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 record2=batchRead.value.find((candidate)=>candidate.laneId===laneId),ref=record2?.result?.outputRef?.trim()??record2?.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 record2 of state2.prFeedbackVerifications??[])for(let ownership of record2.ownership){let batchRead=findByBatchIdDetailed(directory,record2.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 ${record2.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 record2={batchId:event.batchId,lanes:event.lanes,validatedAt:event.validatedAt},nextDispatches=[...dispatches,record2];return applied({...state2,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record2},[{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 readFileSync40,statSync as statSync38}from"node:fs";import*as fsp8 from"node:fs/promises";import*as path103 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:[path103.join(".swarm",workflowCheckoutMutationLockRelativePath()),path103.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(record2){if(record2.status!=="cancelled"&&record2.status!=="stale"&&record2.status!=="error")return!1;return record2.terminalResult?.result.workflowLaneFailureClass==="liveness"||record2.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((record3)=>record3.subagentSessionId===child&&record3.correlationId===child&&(record3.mode==="swarm-pr-review:base"||record3.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,record2=repairRecord??preliminary[0],childOfRecord=record2.subagentSessionId;if(!record2.batchId||!record2.laneId)return{status:"rejected",reason:"delegation batch/lane provenance is missing"};if(input.batchId!==void 0&&input.batchId!==record2.batchId||input.laneId!==void 0&&input.laneId!==record2.laneId)return{status:"rejected",reason:"delegation batch/lane identity mismatch"};let{batchId,laneId}=record2;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(record2.jobId),dispatchWorkflowRevision=record2.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(record2.mode!=="swarm-pr-review:base"&&record2.mode!=="swarm-pr-review:micro"||!sameProjectRoot(record2.workspace?.directory??"",directory))return{status:"rejected",reason:"delegation mode or workspace mismatch"};let ownedWorkflowLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:[];if(!record2.workflowLane||ownedWorkflowLanes.length===0)return{status:"rejected",reason:"delegation ownership is missing"};let semanticEnvelopeDigest=prReviewLaneResultEnvelopeDigest(parsedResult.data),existingReceiptDigest=record2.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:record2.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record2.workflowLane,ownedWorkflowLanes,baseSha:state2.prReviewBaseSha,headSha:state2.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:childOfRecord,generation:record2.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data,...repairRecord?{submittedBy:"workflow_parent",submittedByParentSessionId:parentSessionId,laneTerminalStateAtSubmission:record2.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(error49){if(error49.code==="ENOENT")return;throw error49}let entriesRead=0,scanError,closeError;try{for(;;){let entry=await handle.read();if(!entry)break;if(entriesRead+=1,entriesRead>MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES)throw Error("BLOCKED: PR workflow gate inventory exceeds the bounded checkout-restoration scan; clear stale workflow state before retrying");if(!/\.json$/i.test(entry.name))continue;if(!entry.isFile())throw Error("BLOCKED: PR workflow gate inventory contains a non-regular state entry; checkout restoration cannot prove project inactivity");let statePath2=validateSwarmPath(directory,path103.join(WORKFLOW_GATE_DIR,entry.name)),state2=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state2)continue;let expectedName=path103.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(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,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(error49){return{statuses:new Map,degradedReason:error49===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 record2 of records){let subagentSessionId=record2.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=(record2,reason)=>({laneId:record2.laneId??record2.correlationId,pendingMs:Math.max(0,now-record2.updatedAt),hostStatus:"unknown",stalledSuspect:!0,degradedReason:reason});try{now=_test_exports2.nowMs();let threshold=_test_exports2.pendingLaneLivenessThresholdMs;if(pastThreshold=records.filter((record2)=>(record2.status==="pending"||record2.status==="running"||record2.status==="ingesting")&&now-record2.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((record2)=>degraded(record2,"probe-skipped-no-budget"));let probe2=await probePrWorkflowLaneSessionStatusTypes(directory,pastThreshold,budgetMs),advisories=[];for(let record2 of pastThreshold){let pendingMs=now-record2.updatedAt,laneId=record2.laneId??record2.correlationId;if(probe2.degradedReason){advisories.push({laneId,pendingMs,hostStatus:"unknown",stalledSuspect:!0,degradedReason:probe2.degradedReason});continue}let subagentSessionId=record2.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((record2)=>degraded(record2,"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(record2){return record2.laneId??record2.subagentSessionId??"unknown"}function isOpenPrWorkflowLane(record2,sessionID){return record2.parentSessionId===sessionID&&record2.mode?.startsWith("swarm-pr-")===!0&&(record2.status==="pending"||record2.status==="running")}async function abortLaneSessionForWatchdog(record2){let session=_test_exports2.getSessionOps(),abortOp=session?.abort;if(!session||typeof abortOp!=="function"||!record2.subagentSessionId)return!1;try{return await withTimeout(abortOp.call(session,{path:{id:record2.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(`
1282
1282
  `)){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((record2)=>{if(!record2.subagentSessionId)return!1;let type=sessionTypes.get(record2.subagentSessionId);return type==="busy"||type==="retry"});if(candidates.length===0)return;let lastEscalations=lastWatchdogEscalationsByLaneLabel(directory,sessionID),escalated=[],progressed=[],firstEscalatedSteps=0,firstEscalatedTokens=0;for(let record2 of candidates){let activity=null;try{activity=await laneLivenessWatchdogSurface.readLaneActivity(directory,record2.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(record2);continue}let label=prWorkflowLaneLabel(record2),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(record2)}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 record2 of laneRead.records){if(!isOpenPrWorkflowLane(record2,sessionID))continue;if(now-record2.updatedAt>horizon.horizonMs)presumedStale.push(record2);else open7.push(record2)}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 record2 of presumedStale){let type=record2.subagentSessionId?sessionTypes.get(record2.subagentSessionId):void 0;if(deadlineActive&&type!=="retry")deadlineLanes.push(record2),settled.push(record2);else if(record2.subagentSessionId&&probe2.alive.has(record2.subagentSessionId))probeRetained.push(record2);else if(deadlineActive)deadlineLanes.push(record2),settled.push(record2);else settled.push(record2)}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((record2)=>record2.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 record2 of deadlineLanes){if((record2.subagentSessionId?sessionTypes.get(record2.subagentSessionId):void 0)!=="busy"||!record2.subagentSessionId)continue;if(priorDeadlineLabels.has(prWorkflowLaneLabel(record2)))continue;if(abortAttempted=!0,await abortLaneSessionForWatchdog(record2))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((record2)=>record2.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 record2 of finalizeRead.records){if(isOpenPrWorkflowLane(record2,sessionID))outcome.sessionOpenLaneIds.push(record2.correlationId);if(!targeted.has(record2.correlationId))continue;if(record2.status==="stale")outcome.finalizedLaneIds.push(record2.correlationId);else if(record2.status!=="pending"&&record2.status!=="running")outcome.sparedLaneDescriptions.push(`${record2.correlationId} (${record2.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(error49){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:(error49 instanceof Error?error49.message:String(error49)).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 error49}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(error49){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 error49}}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((record2)=>record2.parentSessionId===state2.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0)throw Error(`BLOCKED: PR_FEEDBACK rebind refused while ${openLanes.length} PR workflow lane(s) are still in flight; collect their results first.`);if(normalizedHead===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((record2)=>record2.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((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record2.status)||record2.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(error49){return{live:!1,reason:error49===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 record2 of records){let type=response.data[record2.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((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record2.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((record3)=>record3.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 record2={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:record2.lanes,maxBatches:MAX_WORKFLOW_BATCHES,validatedAt:record2.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 set2 of sets)for(let dimension of set2)if(!bitOf.has(dimension))bitOf.set(dimension,bitOf.size);let universeSize=bitOf.size;if(universeSize===0)return 0;let distinctMasks=new Set,largestSetSize=1;for(let set2 of sets){let mask=0,size=0;for(let dimension of set2){let bit=1<<bitOf.get(dimension);if((mask&bit)===0)size+=1;mask|=bit}if(mask===0)continue;distinctMasks.add(mask),largestSetSize=Math.max(largestSetSize,size)}if(universeSize>MAX_COVER_UNIVERSE_BITS)return Math.ceil(universeSize/largestSetSize);let full=(1<<universeSize)-1,unreachable=universeSize+1,best=Array(full+1).fill(unreachable);best[0]=0;for(let mask=0;mask<full;mask+=1){let steps=best[mask];if(steps===unreachable)continue;for(let setMask of distinctMasks){let next=mask|setMask;if(next===mask)continue;if(best[next]>steps+1)best[next]=steps+1}}return best[full]}function tierLBackingLaneCount(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(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),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 record2 of batchRead.value){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(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 record2={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,record2],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(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),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((record3)=>record3.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 record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};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,checks3,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(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash53("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,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:[...checks3],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),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state2,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};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((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let 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(error49){return{kind:"unresolvable",component,detail:String(error49?.message??error49)}}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 url2=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,active.remoteName);if(!url2)return{kind:"unresolvable",component,detail:`remote "${active.remoteName}" URL could not be resolved`};return url2===active.remoteUrlIdentity?{kind:"intact"}:{kind:"drift",component,detail:`approved remote URL identity ${active.remoteUrlIdentity} vs current ${url2}`}}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 check2=await verifyPublicationIdentityComponent(directory,state2,active,component);if(check2.kind!=="intact")return check2}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 join82 of active.evidence.batches){let batch=[...state2.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===join82.phase);if(!batch||batch.batchId!==join82.batchId||batch.laneId!==join82.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(`
1283
1283
  `)}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(`
1284
1284
  `)){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 check2=await checkPublicationIdentity(directory,state2,active);if(check2.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check2.component}" (${check2.detail}); the push was not admitted`);if(check2.kind==="drift"){let invalidation=await applyPublicationInvalidationWhileLocked(directory,state2,`drift:${check2.component}`,{drift:check2});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check2.component}: ${check2.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(error49){if(error49 instanceof Error&&error49.message.startsWith("BLOCKED: PR_FEEDBACK publication generation"))throw error49}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 check2=await checkPublicationIdentity(directory,state2,active);if(check2.kind==="unresolvable")throw Error(`BLOCKED: PR_FEEDBACK could not verify the armed publication identity component "${check2.component}" (${check2.detail}); the armed window is unchanged and fails closed. Resolve the verification failure and retry.`);if(check2.kind==="drift"){let invalidation=await invalidatePublicationGeneration(directory,sessionID,`drift:${check2.component}`,{drift:check2,driftReverification:!0});throw Error(`BLOCKED: PR_FEEDBACK publication generation ${invalidation.generation.generation} was INVALIDATED because approved content identity drifted (${check2.component}: ${check2.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(error49){throw Error(`BLOCKED: invalid PR_REVIEW trigger_evaluation: ${error49 instanceof Error?error49.message:String(error49)}`)}let state2=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;if(state2.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state2.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return 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=(record2,expected)=>{if(record2.severity===expected)return;let raw=record2.severity,actual=raw===void 0?"(omitted)":raw===null?"(null)":raw===""?"(empty)":`"${raw}"`;report(record2.finding_id,"severity",`"${expected}"`,actual)},reportRiskMetadata=(record2,reviewer)=>{if(record2.status!=="CONFIRMED")return;let expectedImpact=reviewer.riskImpact??"UNKNOWN",expectedTags=reviewer.riskTags??[],actualImpact=record2.risk_impact??"UNKNOWN",actualTags=record2.risk_tags??[];if(actualImpact!==expectedImpact)report(record2.finding_id,"risk_impact",`"${expectedImpact}"`,record2.risk_impact===void 0?"(omitted)":`"${actualImpact}"`);if(actualTags.join(",")!==expectedTags.join(","))report(record2.finding_id,"risk_tags",JSON.stringify(expectedTags),record2.risk_tags===void 0?"(omitted)":JSON.stringify(actualTags))};if(boundary==="post_explorer"){let candidateSeverities=derivePrReviewCandidateSeverities(directory,state2,await createPrReviewGateContext2(directory,state2));for(let record2 of records){if(record2.status!=="PENDING")report(record2.finding_id,"status",'"PENDING"',`"${record2.status}"`);if(record2.next_action!=="route_to_reviewer")report(record2.finding_id,"next_action",'"route_to_reviewer"',`"${record2.next_action}"`);let candidateSeverity=candidateSeverities.get(record2.finding_id);if(candidateSeverity){reportSeverity(record2,candidateSeverity);continue}if(record2.finding_id===PR_REVIEW_CLEAN_SENTINEL_ID){reportSeverity(record2,"NONE");continue}violations.push({findingId:record2.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 record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer){violations.push({findingId:record2.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(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.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(record2.next_action!==expectedAction)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity),reportRiskMetadata(record2,reviewer);continue}if(!requiresCritic){let expectedAction=reviewer.classification==="CONFIRMED"||reviewer.classification==="PRE_EXISTING"?"report":reviewer.classification==="DISPROVED"?"suppress_with_reason":"route_to_reviewer";if(record2.status!==expectedStatus)report(record2.finding_id,"status",`"${expectedStatus}"`,`"${record2.status}"`);if(record2.next_action!==expectedAction)report(record2.finding_id,"next_action",`"${expectedAction}"`,`"${record2.next_action}"`);reportSeverity(record2,reviewer.severity),reportRiskMetadata(record2,reviewer);continue}let critic=criticVerdicts?.get(record2.finding_id);if(!critic){reportSeverity(record2,reviewer.severity),reportRiskMetadata(record2,reviewer),violations.push({findingId:record2.finding_id,detail:"no authoritative critic verdict (absent from the settled critic map)"});continue}if(critic.status==="DISPROVED"){if(record2.status!=="DISPROVED")report(record2.finding_id,"status",'"DISPROVED"',`"${record2.status}"`);if(record2.next_action!=="suppress_with_reason")report(record2.finding_id,"next_action",'"suppress_with_reason"',`"${record2.next_action}"`)}else{if(record2.status!=="CONFIRMED")report(record2.finding_id,"status",'"CONFIRMED"',`"${record2.status}"`);if(!["report","handoff_to_feedback"].includes(record2.next_action))report(record2.finding_id,"next_action",'"report" or "handoff_to_feedback"',`"${record2.next_action}"`)}reportSeverity(record2,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):
@@ -7150,7 +7150,7 @@ ${modeSignal}`:message,usePromptDelivery=config3.event_delivery==="prompt"&&_int
7150
7150
  `),constraints=[];for(let line of lines){if(constraints.length>=MAX_CONSTRAINTS_PER_DOC)break;let trimmed=line.trim();if(!trimmed)continue;if(isConstraintLine(trimmed)){let cleaned=stripMarkdown(trimmed),len=cleaned.length;if(len>=MIN_LESSON_LENGTH&&len<=MAX_CONSTRAINT_LENGTH)constraints.push(cleaned)}}return constraints}async function extractDocConstraints(directory,taskFiles,taskDescription){let manifestPath2=path288.join(directory,".swarm","doc-manifest.json"),manifest;try{let content=await readFile55(manifestPath2,"utf-8");manifest=JSON.parse(content)}catch{manifest=(await scanDocIndex(directory)).manifest}let knowledgePath=resolveSwarmKnowledgePath(directory),existingEntries=await readKnowledge(knowledgePath),taskContext=[...taskFiles,taskDescription].join(" "),taskBigrams=wordBigrams(normalize4(taskContext)),extractedCount=0,skippedCount=0,details=[];for(let docFile of manifest.files){let docContext=`${docFile.path} ${docFile.title} ${docFile.summary}`,docBigrams=wordBigrams(normalize4(docContext)),score=jaccardBigram(taskBigrams,docBigrams);if(score<=RELEVANCE_THRESHOLD){skippedCount++;continue}let fullContent;try{fullContent=await readFile55(path288.join(directory,docFile.path),"utf-8")}catch{skippedCount++;continue}let constraints=extractConstraintsFromContent(fullContent);if(constraints.length===0){skippedCount++;continue}let docDetails={path:docFile.path,score,constraints:[]};for(let constraint of constraints)if(!findNearDuplicate(constraint,existingEntries,DEDUP_THRESHOLD2)){let entry={id:crypto14.randomUUID(),tier:"swarm",lesson:constraint,category:"architecture",tags:["doc-scan",path288.basename(docFile.path)],scope:"global",confidence:0.5,status:"candidate",confirmed_by:[],project_name:"",retrieval_outcomes:{applied_count:0,succeeded_after_count:0,failed_after_count:0},schema_version:1,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),auto_generated:!0,hive_eligible:!1};await appendKnowledge(knowledgePath,entry),existingEntries.push(entry),extractedCount++,docDetails.constraints.push(constraint)}if(docDetails.constraints.length>0)details.push(docDetails);else skippedCount++}return{extracted:extractedCount,skipped:skippedCount,details}}var SKIP_DIRECTORIES3,SKIP_PATTERNS,MAX_SUMMARY_LENGTH=200,MAX_INDEXED_FILES=100,READ_LINES_LIMIT=30,MIN_LESSON_LENGTH=15,MAX_CONSTRAINTS_PER_DOC=5,MAX_CONSTRAINT_LENGTH=200,RELEVANCE_THRESHOLD=0.1,DEDUP_THRESHOLD2=0.6,CONSTRAINT_PATTERNS,ACTION_WORDS,doc_scan,doc_extract;var init_doc_scan=__esm(()=>{init_zod();init_schema();init_knowledge_store();init_create_tool();SKIP_DIRECTORIES3=new Set(["node_modules",".git",".swarm",".swarm-worktrees","dist","build",".next","vendor","bazel-out","bazel-bin","bazel-genfiles","bazel-testlogs",".gradle","target"]),SKIP_PATTERNS=[/\.test\./,/\.spec\./,/\.d\.ts$/];CONSTRAINT_PATTERNS=[/\bMUST\b/,/\bMUST NOT\b/,/\bSHOULD\b/,/\bSHOULD NOT\b/,/\bDO NOT\b/,/\bALWAYS\b/,/\bNEVER\b/,/\bREQUIRED\b/],ACTION_WORDS=/\b(must|should|don't|avoid|ensure|use|follow)\b/i;doc_scan=createSwarmTool({description:"Scan project documentation files and build an index manifest. Caches results in .swarm/doc-manifest.json for fast subsequent scans.",args:{force:exports_external.boolean().optional().describe("Force re-scan even if cache is valid")},execute:async(args2,directory)=>{let force=!1;try{if(args2&&typeof args2==="object"){if(args2.force===!0)force=!0}}catch{}if(force){let manifestPath2=path288.join(directory,".swarm","doc-manifest.json");try{fs164.unlinkSync(manifestPath2)}catch{}}let{manifest,cached:cached3}=await scanDocIndex(directory);return JSON.stringify({success:!0,files_count:manifest.files.length,cached:cached3,manifest},null,2)}}),doc_extract=createSwarmTool({description:"Extract actionable constraints from project documentation relevant to the current task. Scans docs via doc-manifest, scores relevance via Jaccard bigram similarity, and stores non-duplicate constraints in .swarm/knowledge.jsonl.",args:{task_files:exports_external.array(exports_external.string()).describe("List of file paths involved in the current task"),task_description:exports_external.string().describe("Description of the current task")},execute:async(args2,directory)=>{let taskFiles=[],taskDescription="";try{if(args2&&typeof args2==="object"){let obj=args2;if(Array.isArray(obj.task_files))taskFiles=obj.task_files.filter((f)=>typeof f==="string");if(typeof obj.task_description==="string")taskDescription=obj.task_description}}catch{}if(taskFiles.length===0&&!taskDescription)return JSON.stringify({success:!1,error:"task_files or task_description is required"});let result=await extractDocConstraints(directory,taskFiles,taskDescription);return JSON.stringify({success:!0,...result},null,2)}})});var exports_knowledge_recall={};__export(exports_knowledge_recall,{knowledge_recall:()=>knowledge_recall,_internals:()=>_internals231});var knowledge_recall,_internals231;var init_knowledge_recall=__esm(()=>{init_zod();init_config();init_schema();init_knowledge_events();init_knowledge_receipt_ledger();init_knowledge_types();init_search_knowledge();init_knowledge_diagnostics();init_logger();init_create_tool();knowledge_recall=createSwarmTool({allowWorkingDirectoryOverride:!0,description:"Performs semantic natural-language search across the knowledge base for relevant past decisions, patterns, and lessons learned. Returns ranked results via the unified hybrid retrieval service and a trace_id for knowledge_receipt. This is the tool to use when the user has a QUESTION about what the knowledge base contains. For structured filter-based retrieval (by category, status, or score), use `knowledge_query` instead.",args:{query:exports_external.string().min(3).describe("Natural language search query"),top_n:exports_external.number().int().min(1).max(20).optional().describe("Maximum results to return (default: 5)"),tier:exports_external.enum(["all","swarm","hive"]).optional().describe("Knowledge tier to search (default: 'all')"),debug:exports_external.boolean().optional().describe("Include path/version/health debug metadata in the response"),repair_re_evaluation:exports_external.object({repair_id:exports_external.string().uuid(),phase:exports_external.string().min(1).max(256),task_id:exports_external.string().min(1).max(256).optional(),scope_complete:exports_external.boolean()}).optional().describe("Architect-only explicit completion of a repaired receipt scope. The query must comprehensively re-evaluate the exact affected phase/session scope.")},execute:async(args2,directory,ctx)=>{let queryInput,topNInput,tierInput,debugInput,repairInput;try{if(args2&&typeof args2==="object"){let obj=args2;queryInput=obj.query,topNInput=obj.top_n,tierInput=obj.tier,debugInput=obj.debug,repairInput=obj.repair_re_evaluation}}catch{}let wantDebug=debugInput===!0,repairReevaluation;if(repairInput!==void 0){if(stripKnownSwarmPrefix(ctx?.agent??"")!=="architect"||typeof repairInput!=="object"||repairInput===null)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_ARCHITECT_ONLY",error:"Only the architect may complete an explicit receipt repair re-evaluation."});let candidate2=repairInput;if(typeof candidate2.repair_id!=="string"||!candidate2.repair_id||typeof candidate2.phase!=="string"||!candidate2.phase||candidate2.scope_complete!==!0||candidate2.task_id!==void 0&&typeof candidate2.task_id!=="string")return JSON.stringify({results:[],total:0,unverifiable:!0,code:"RECEIPT_REEVALUATION_PROOF_INVALID",error:"Explicit re-evaluation requires repair_id, exact phase, and scope_complete=true."});repairReevaluation={repair_id:candidate2.repair_id,phase:candidate2.phase,scope_complete:!0,...typeof candidate2.task_id==="string"?{task_id:candidate2.task_id}:{}}}if(typeof queryInput!=="string"||queryInput.length<3)return JSON.stringify({results:[],total:0,error:"query must be a string with at least 3 characters"});let topN=5;if(typeof topNInput==="number"&&Number.isInteger(topNInput))topN=Math.max(1,Math.min(20,topNInput));let tier="all";if(tierInput==="swarm"||tierInput==="hive")tier=tierInput;let knowledgeConfig=KnowledgeConfigSchema.parse({});try{let{config:config3}=loadPluginConfigWithMeta(directory);knowledgeConfig=KnowledgeConfigSchema.parse(config3.knowledge??{})}catch{}let{trace_id,results}=await searchKnowledge({directory,config:knowledgeConfig,query:queryInput,mode:"manual",agent:ctx?.agent??"unknown",sessionId:ctx?.sessionID??"unknown",tier,maxResults:topN,applyScopeFilter:!1,forceReadHive:!0,applyRoleScope:!1,emitEvent:!1}),sessionId=ctx?.sessionID??"unknown";if(results.length>0){let membership=await commitDisplayedMembership(directory,{trace_id,session_id:sessionId,exposure_kind:"manual_recall",agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation,entries:results.map((entry,index)=>({entry_id:entry.id,critical:entry.directive_priority==="critical"&&isActiveStatus(entry.status),rank:index+1,score:entry.finalScore}))});if(!membership.ok||membership.memberships.some((item)=>item.terminal))return JSON.stringify({results:[],total:0,unverifiable:!0,code:membership.ok?"terminal_trace_reuse":membership.code,error:membership.ok?"retrieval trace was already terminalized":membership.detail})}else{let empty=await commitEmptyRetrieval(directory,{trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",grace_days:knowledgeConfig.receipt_close_grace_days,phase:repairReevaluation?.phase,task_id:repairReevaluation?.task_id,repair_re_evaluation:repairReevaluation});if(!empty.ok)return JSON.stringify({results:[],total:0,unverifiable:!0,code:empty.code,error:empty.detail});if(!empty.terminal_event_id)return JSON.stringify({results:[],total:0,unverifiable:!0,code:"store_unavailable",error:"empty retrieval terminal did not commit"})}let ranks=Object.fromEntries(results.map((entry,index)=>[entry.id,index+1])),scores=Object.fromEntries(results.map((entry)=>[entry.id,entry.finalScore]));await recordKnowledgeEvent(directory,{type:"retrieved",trace_id,session_id:sessionId,agent:ctx?.agent??"unknown",query:queryInput,retrieval_mode:"manual",result_ids:results.map((entry)=>entry.id),ranks,scores});let scored=results.map((e)=>({id:e.id,confidence:e.confidence,category:e.category,lesson:e.lesson,score:e.finalScore,score_breakdown:e.score_breakdown}));log("[knowledge_recall] completed",{agent:ctx?.agent??"unknown",session_id:ctx?.sessionID??"unknown",query:queryInput,tier,result_count:scored.length,trace_id});let result={results:scored,total:scored.length,trace_id};if(wantDebug)result.debug=await computeKnowledgeDebug(directory);return JSON.stringify(result)}}),_internals231={knowledge_recall}});var exports_prompt_renderer={};__export(exports_prompt_renderer,{renderEnvironmentPrompt:()=>renderEnvironmentPrompt});function renderEnvironmentPrompt(profile,audience){let policy=deriveCommandPolicy(profile),header=["RUNTIME ENVIRONMENT",`- Host OS: ${profile.hostOS}`,`- Shell family: ${profile.shellFamily}`,`- Execution mode: ${profile.executionMode}`,`- Path style: ${profile.pathStyle}`].join(`
7151
7151
  `);if(audience==="coder")return[header,policy.avoidPosixExamples?"- Command policy: Prefer PowerShell-native commands and Node.js APIs. Do not start with POSIX commands (ls, grep, rm, cat, export, pwd) unless the environment profile indicates Docker, WSL, or a POSIX shell.":"- Command policy: Use POSIX-native commands and Node.js APIs.","","EXECUTION ENVIRONMENT AWARENESS","- This session includes a runtime environment profile. Follow it exactly.","- Decision ladder when shell commands are necessary:"," 1. Prefer swarm tools and Node.js fs/path APIs."," 2. Use shell only when the task truly requires it."," 3. When shell commands are needed, match the active shell family above."].join(`
7152
7152
  `);return[header,"- Test execution policy: Always execute tests via the swarm test runner tool.",policy.avoidPosixExamples?" Do not describe POSIX shell setup commands unless the profile indicates Docker, WSL, or POSIX shell.":" Use POSIX semantics for test commands.","","ENVIRONMENT-SPECIFIC TEST EXECUTION RULES",profile.isWindowsNative?"- Native Windows + PowerShell: Assume PowerShell semantics for paths and env vars. Prefer Pester for PowerShell modules where appropriate.":profile.isWindowsDocker?"- Windows + Docker: Host paths are Windows-style; in-container operations use POSIX semantics.":"- Linux/macOS: Use POSIX semantics for all shell-related reasoning.","- In all modes: prefer the swarm test runner over ad hoc shell commands.","- When tests are skipped due to environment issues, explicitly mention the environment profile assumptions in your verdict."].join(`
7153
- `)}var init_prompt_renderer=()=>{};function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync155,readdirSync as readdirSync44,readFileSync as readFileSync128,statSync as statSync89}from"node:fs";import*as path294 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path294.resolve(directory),resolved=path294.resolve(baseDir,concrete),rel3=path294.relative(baseDir,resolved);if(rel3.startsWith("..")||path294.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path294.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path294.join(dir,name);if(existsSync155(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve114)=>setTimeout(()=>resolve114("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync44(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path294.join(dir,entry.name),relPath=path294.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync89(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync128(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path294.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path294.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals240.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals240.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals240.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals240.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals240,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals240={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash101}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash101("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash101("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash101("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash101("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals259,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs183 from"node:fs";import*as path315 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals259.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals259.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals259.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals259.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{inputTokens:costFields.tokens_input,outputTokens:costFields.tokens_output,cacheReadTokens:costFields.tokens_cache}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path315.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs183.existsSync(filePath))return null;let parsed=JSON.parse(fs183.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path315.join(directory,".swarm");fs183.mkdirSync(swarmDir,{recursive:!0});let filePath=path315.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs183.rmSync(filePath,{force:!0});else fs183.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals259;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals259={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals281});import*as fs204 from"node:fs";import*as path339 from"node:path";function mtimeMsOrNull(absPath){try{return fs204.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path339.resolve(directory),resolved=path339.resolve(root,anchor),rel3=path339.relative(root,resolved);if(rel3.startsWith("..")||path339.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path339.resolve(directory),outAbs=path339.resolve(root,outDir),outRel=path339.relative(root,outAbs);if(outRel.startsWith("..")||path339.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path339.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path339.join(outDir,relFile));else checkedDocs.push(path339.join(outDir,relFile))}let traceabilityAbs=path339.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs204.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs204.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section of registry4.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals281;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path339.join("reference","reference-impl.md"),"idiom-notes":path339.join("reference","idiom-notes.md")},TRACEABILITY_REL=path339.join("reference","traceability.json");_internals281={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals314,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs238 from"node:fs";import*as path382 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs238.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs238.accessSync(path382.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs238.readFileSync(path382.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals314.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals314.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals314;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals314={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash116}from"node:crypto";import{mkdirSync as mkdirSync101,writeFileSync as writeFileSync66}from"node:fs";import*as path383 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs149 from"node:fs";import*as path271 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path271.resolve(this.directory,".swarm")}getPlanJsonPath(){return path271.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs149.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs149.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs149.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs149.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs149.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals53.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals53.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path271.join(swarmDir,"plan.json"),markerPath=path271.join(swarmDir,".plan-write-marker"),planStats=fs149.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs149.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve106,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve106(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash96}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash95}from"node:crypto";import*as fs151 from"node:fs";import*as path273 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25610(value){return createHash95("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25610(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs151.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs151.openSync(filePath,fs151.constants.O_RDONLY|(fs151.constants.O_NOFOLLOW??0));let openedStat=fs151.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs151.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs151.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs151.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs151.promises.open(filePath,fs151.constants.O_RDONLY|(fs151.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25610(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs151.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs151.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs151.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs151.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs151.promises.mkdir(path273.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25610(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25610(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25610(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace);return{...check3,ok:!check3.stale}}function compareStageBWorkspace(record3,actualWorkspace){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace)}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve106)=>setTimeout(resolve106,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash96("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash96("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_package();init_constants();import*as fs152 from"node:fs";import*as path274 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path274.join(projectDirectory,".swarm"),dest=path274.join(swarmDir,"config.example.json");if(fs152.existsSync(dest))return;if(!fs152.existsSync(swarmDir))fs152.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs152.writeFileSync(dest,`${JSON.stringify(example,null,2)}
7153
+ `)}var init_prompt_renderer=()=>{};function reject(reason,detail,rejected_items){return{ok:!1,rejected:!0,reason,detail,rejected_items}}async function validateReceipt(ctx){let{items,no_relevant_knowledge:noRelevant}=ctx;if(items.length===0&&!noRelevant)return reject("empty_receipt","no items and no_relevant_knowledge is false");if(noRelevant&&items.length>0)return reject("invalid_outcome","no_relevant_knowledge cannot be combined with items");for(let item of items)if(!VALID_OUTCOMES.has(item.outcome))return reject("invalid_outcome",`item ${item.id}: outcome ${item.outcome}`);let traceId=ctx.trace_id||NO_TRACE_SENTINEL;if(traceId===NO_TRACE_SENTINEL){if(items.length>0)return reject("trace_not_found","items filed against the none sentinel trace");let empty=await commitEmptyRetrieval(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,grace_days:ctx.grace_days});if(!empty.ok)return reject(empty.code,empty.detail);return{ok:!0,accepted:[],idempotent_skips:[],trace:null,closes_no_relevant:!0,authoritative_event_ids:{},no_relevant_event_id:empty.terminal_event_id}}let committed=await validateAndCommitTerminalBatch(ctx.directory,{trace_id:traceId,session_id:ctx.session_id,phase:ctx.phase,task_id:ctx.task_id,agent:ctx.agent,cohort_id:ctx.cohort_id,source_link_id:ctx.source_link_id,grace_days:ctx.grace_days,items:items.map((item)=>({entry_id:item.id,outcome:item.outcome,reason:item.reason,source:ctx.source.trim()||"unknown"})),no_relevant_knowledge:noRelevant});if(!committed.ok)return reject(committed.code,committed.detail);let remainingItems=[...items],takeItem=(id,outcome)=>{let index=remainingItems.findIndex((item)=>item.id===id&&(outcome===void 0||item.outcome===outcome));if(index<0)return;return remainingItems.splice(index,1)[0]},accepted=committed.accepted.map((item)=>takeItem(item.entry_id,item.outcome)).filter((item)=>item!==void 0),idempotent_skips=committed.idempotent.map((id)=>takeItem(id)).filter((item)=>item!==void 0),rejected_items=committed.rejected.map((item)=>({item:takeItem(item.entry_id)??{id:item.entry_id,outcome:"ignored"},reason:item.reason}));if(rejected_items.length&&accepted.length===0&&idempotent_skips.length===0)return reject(rejected_items[0].reason,`${rejected_items[0].reason} for id ${rejected_items[0].item.id}`,rejected_items);let queried=await queryLiveMemberships(ctx.directory,{session_id:ctx.session_id,include_terminal:!0,grace_days:ctx.grace_days}),memberships=queried.ok?queried.memberships.filter((membership)=>membership.trace_id===traceId):[],trace=memberships.length?{type:"retrieved",event_id:memberships[0].membership_event_id,trace_id:traceId,timestamp:memberships[0].committed_at,session_id:ctx.session_id,phase:memberships[0].phase,task_id:memberships[0].task_id,agent:memberships[0].agent??ctx.agent,query:"",retrieval_mode:"manual",result_ids:memberships.map((membership)=>membership.entry_id),ranks:Object.fromEntries(memberships.map((membership,index)=>[membership.entry_id,membership.rank??index+1])),scores:Object.fromEntries(memberships.map((membership)=>[membership.entry_id,membership.score??0]))}:null;return{ok:!0,accepted,idempotent_skips,trace,closes_no_relevant:committed.closes_no_relevant,authoritative_event_ids:Object.fromEntries(committed.accepted.map((item)=>[item.entry_id,item.event_id])),...committed.terminal_event_id?{no_relevant_event_id:committed.terminal_event_id}:{},...rejected_items.length?{rejected_items}:{}}}var NO_TRACE_SENTINEL="none",VALID_OUTCOMES;var init_knowledge_receipt_validator=__esm(()=>{init_knowledge_receipt_ledger();VALID_OUTCOMES=RECEIPT_TERMINAL_OUTCOMES});function isTaskTool3(tool3){return tool3==="Task"||tool3==="task"}function resolveDelegateAckTaskId(args2,knownPlanTaskIds,planContextOverLimit=!1){let resolved=resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit);return resolved.status==="resolved"?resolved.taskId:void 0}function resolveDelegateAckTaskIdResult(args2,knownPlanTaskIds,planContextOverLimit=!1){return resolveTaskId(args2,{policy:"attribution",knownPlanTaskIds,planContextOverLimit})}async function appendUnacknowledgedCritical(directory,record3){let filePath=validateSwarmPath(directory,"unacknowledged-criticals.jsonl");await appendCappedJsonl(filePath,JSON.stringify(record3),{maxEntries:resolveRetentionCap("MAX_UNACKNOWLEDGED_CRITICALS",MAX_UNACKNOWLEDGED_CRITICALS),onPrune:(dropped)=>{warn(`unacknowledged-criticals audit at cap: dropped ${dropped} oldest ${dropped===1?"entry":"entries"} (FIFO bound MAX_UNACKNOWLEDGED_CRITICALS)`)}})}async function reconcileShownDirectives(params){let result={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};try{let shown=params.shown;if(shown.length===0)return result;let shownById=new Map(shown.map((d)=>[d.id,d])),criticalIds=shown.filter((d)=>d.priority==="critical").map((d)=>d.id),acks=parseAcknowledgments(params.transcript),ackedIds=new Set,violatedIds=new Set,sessionId=params.sessionId,taskId=params.taskId,traceId=params.traceId??"legacy-unverifiable",isLegacyPrompt=params.traceId===void 0,cohortId,linkId;try{cohortId=await ensureCohortIdCached(params.directory,sessionId),linkId=readLinkPointer(params.directory)?.linkId}catch{}let ackItems=[],ackByItemId=new Map;for(let ack of acks){if(!shownById.has(ack.id))continue;if(ackedIds.add(ack.id),!isLegacyPrompt&&ack.trace_id!==traceId)continue;if(ack.result==="applied"||ack.result==="ignored"||ack.result==="violated"||ack.result==="n_a"||ack.result==="contradicted")ackItems.push({id:ack.id,outcome:ack.result,reason:ack.reason}),ackByItemId.set(ack.id,ack)}let eventIdByKnowledgeId=new Map;if(isLegacyPrompt)for(let ack of acks){if(!shownById.has(ack.id))continue;if(!ackByItemId.has(ack.id))continue;ackedIds.add(ack.id)}else{let validation2=await validateReceipt({directory:params.directory,trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",cohort_id:cohortId,source_link_id:linkId,items:ackItems,no_relevant_knowledge:!1});if(validation2.ok){for(let item of validation2.accepted){let ack=ackByItemId.get(item.id);if(!ack)continue;ackedIds.add(item.id),await recordKnowledgeEvent(params.directory,{type:item.outcome,trace_id:traceId,knowledge_id:item.id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:ack.reason});let authoritativeEventId=validation2.authoritative_event_ids[item.id];if(authoritativeEventId)eventIdByKnowledgeId.set(item.id,authoritativeEventId);if(item.outcome==="violated")violatedIds.add(item.id);result.emitted.push({id:item.id,type:item.outcome})}for(let item of validation2.idempotent_skips)ackedIds.add(item.id);for(let rejected2 of validation2.rejected_items??[])ackedIds.add(rejected2.item.id)}if(!validation2.ok)for(let id of ackByItemId.keys())ackedIds.add(id)}try{let now2=new Date().toISOString(),evidenceRecords=[];for(let[kid,eid]of eventIdByKnowledgeId){let ack=ackByItemId.get(kid);if(!ack||!cohortId)continue;let outcome=ack.result;if(outcome!=="applied"&&outcome!=="violated"&&outcome!=="contradicted")continue;evidenceRecords.push({cohort_id:cohortId,source_link_id:linkId,entry_id:kid,retrieval_trace_id:traceId,receipt_outcome:outcome,receipt_source:"delegate",receipt_event_id:eid,phase:void 0,timestamp:now2})}await appendPromotionEvidence(params.directory,evidenceRecords)}catch{}let missingCriticalIds=criticalIds.filter((id)=>!ackedIds.has(id)),committedMissingCriticalIds=new Set;if(!isLegacyPrompt&&missingCriticalIds.length>0){let committed=await validateAndCommitTerminalBatch(params.directory,{trace_id:traceId,session_id:sessionId,task_id:taskId,agent:params.agent,cohort_id:cohortId,source_link_id:linkId,items:missingCriticalIds.map((entry_id)=>({entry_id,outcome:"violated",source:"delegate",reason:"unacknowledged"}))});if(committed.ok)committedMissingCriticalIds=new Set(committed.committed.map((item)=>item.entry_id))}for(let id of missingCriticalIds){if(!committedMissingCriticalIds.has(id))continue;result.unacknowledgedCriticals.push(id),await recordKnowledgeEvent(params.directory,{type:"violated",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"unacknowledged"}),violatedIds.add(id),result.emitted.push({id,type:"violated"});try{await appendUnacknowledgedCritical(params.directory,{timestamp:new Date().toISOString(),knowledge_id:id,agent:params.agent,session_id:sessionId,task_id:taskId,reason:"unacknowledged"})}catch{}}let silentEvents=[];for(let[id,directive]of shownById){if(directive.priority==="critical")continue;if(ackedIds.has(id))continue;if(params.replay===!0)continue;result.unacknowledgedNonCritical.push(id),silentEvents.push({type:"unacknowledged",trace_id:traceId,knowledge_id:id,session_id:sessionId,task_id:taskId,agent:params.agent,source:"delegate",reason:"no_ack_marker"}),result.emitted.push({id,type:"unacknowledged"})}if(silentEvents.length>0)await recordKnowledgeEventsBatch(params.directory,silentEvents);if(violatedIds.size>0)await escalateViolatedEntries(params.directory,[...violatedIds])}catch{}return result}async function collectDelegateAcks(params){let shown=parseDelegateDirectiveBlock(params.prompt);if(shown.length===0)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};let sessionId=params.sessionId;if(!sessionId)return{emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],unverifiable:{code:"missing_session_id",detail:"Delegate acknowledgments require a real host session id"}};let traceId=parseDelegateDirectiveTraceId(params.prompt)??void 0,taskId=params.taskIdResolution?params.taskIdResolution.status==="resolved"?params.taskIdResolution.taskId:void 0:params.taskId??resolveDelegateAckTaskId({prompt:params.prompt});return reconcileShownDirectives({directory:params.directory,shown,traceId,transcript:params.transcript,agent:params.agent,sessionId,taskId})}async function collectLaneDelegateAcks(params){let empty={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[],phases:[]};try{let memberships=await queryLiveMemberships(params.directory,{session_id:params.sessionId,exposure_kind:"delegate_directive",include_terminal:!0});if(!memberships.ok)return empty;let byTrace=new Map,phases=new Set;for(let membership of memberships.memberships){let group=byTrace.get(membership.trace_id)??[];if(group.push(membership),byTrace.set(membership.trace_id,group),membership.phase)phases.add(membership.phase)}let combined={emitted:[],unacknowledgedCriticals:[],unacknowledgedNonCritical:[]};for(let[traceId,group]of byTrace){let taskId=group.find((m)=>m.task_id)?.task_id,outcome=await reconcileShownDirectives({directory:params.directory,shown:group.map((m)=>({id:m.entry_id,priority:m.critical?"critical":"medium"})),traceId,transcript:params.transcript,agent:params.agent,sessionId:params.sessionId,taskId,replay:params.replay});if(combined.emitted.push(...outcome.emitted),combined.unacknowledgedCriticals.push(...outcome.unacknowledgedCriticals),combined.unacknowledgedNonCritical.push(...outcome.unacknowledgedNonCritical),outcome.unverifiable)combined.unverifiable=outcome.unverifiable}return{...combined,phases:[...phases]}}catch{return empty}}async function collectDelegateAcksAfter(directory,input,output){if(!isTaskTool3(input.tool))return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let agent=parseDelegationArgs(input.args)?.targetAgent??"unknown",sessionId=typeof input.sessionID==="string"?input.sessionID:void 0,planTaskIdOptions=toTaskIdPlanContextOptions(await loadPlanTaskIdContext(directory)),taskIdResolution=resolveDelegateAckTaskIdResult(argsRecord??{prompt},planTaskIdOptions.knownPlanTaskIds,planTaskIdOptions.planContextOverLimit);await collectDelegateAcks({directory,prompt,transcript,agent,sessionId,taskIdResolution})}var MAX_UNACKNOWLEDGED_CRITICALS=500;var init_delegate_ack_collector=__esm(()=>{init_caps();init_jsonl_cap();init_logger();init_cohort_cache();init_knowledge_application();init_knowledge_escalator();init_knowledge_events();init_knowledge_injector();init_knowledge_link();init_knowledge_receipt_ledger();init_knowledge_receipt_validator();init_plan_task_id_context();init_promotion_evidence_store();init_skill_propagation_gate();init_task_id_resolver();init_utils2()});import{existsSync as existsSync155,readdirSync as readdirSync44,readFileSync as readFileSync128,statSync as statSync89}from"node:fs";import*as path294 from"node:path";function validateRepoRelativeGlob(directory,value){let v=value.trim();if(!v)return null;if(v.includes("\x00"))return null;if(v.startsWith("/")||/^[A-Za-z]:[\\/]/.test(v)||v.startsWith("\\"))return null;if(v.split(/[/\\]/).some((s)=>s===".."))return null;let globStart=v.search(/[*?{[]/),concrete=globStart===-1?v:v.slice(0,globStart);if(concrete){let baseDir=path294.resolve(directory),resolved=path294.resolve(baseDir,concrete),rel3=path294.relative(baseDir,resolved);if(rel3.startsWith("..")||path294.isAbsolute(rel3))return null}return v}function findBinaryInPath(binary){let candidates=process.platform==="win32"?[`${binary}.exe`,`${binary}.cmd`,`${binary}.bat`,binary]:[binary];for(let dir of(process.env.PATH??"").split(path294.delimiter)){if(!dir)continue;for(let name of candidates){let candidate2=path294.join(dir,name);if(existsSync155(candidate2))return candidate2}}return null}function safeChildEnv(){let env={};if(process.env.PATH)env.PATH=process.env.PATH;if(process.env.HOME)env.HOME=process.env.HOME;if(process.env.SystemRoot)env.SystemRoot=process.env.SystemRoot;if(process.env.TEMP)env.TEMP=process.env.TEMP;if(process.env.TMP)env.TMP=process.env.TMP;return env}async function runArgv(argv,cwd){let proc=bunSpawn(argv,{stdin:"ignore",stdout:"pipe",stderr:"pipe",cwd,env:safeChildEnv()}),finished=!1;try{let timeout=new Promise((resolve114)=>setTimeout(()=>resolve114("timeout"),PREDICATE_TIMEOUT_MS));if(await Promise.race([proc.exited,timeout])==="timeout")return{exitCode:null,stdout:"",stderr:"",timedOut:!0};let[stdout,stderr]=await Promise.all([proc.stdout.text().catch(()=>""),proc.stderr.text().catch(()=>"")]);return finished=!0,{exitCode:proc.exitCode,stdout,stderr,timedOut:!1}}finally{if(!finished)try{proc.kill()}catch{}}}async function runGrepPredicate(rest,directory){let lastColon=rest.lastIndexOf(":");if(lastColon<=0||lastColon===rest.length-1)return{result:"error",detail:"grep: expected <regex>:<path-glob>"};let regex=rest.slice(0,lastColon),rawGlob=rest.slice(lastColon+1),glob=validateRepoRelativeGlob(directory,rawGlob);if(glob===null)return{result:"error",detail:`grep: unsafe or empty path-glob "${rawGlob}"`};let pattern;try{pattern=new RegExp(regex,"m")}catch(err){return{result:"error",detail:`grep: invalid regex ${err instanceof Error?err.message:String(err)}`}}let matcher=import_picomatch2.default(glob,{dot:!0}),visited=0,matches=0,walk=(dir)=>{if(visited>=GREP_MAX_FILES)return;let entries2;try{entries2=readdirSync44(dir,{withFileTypes:!0})}catch{return}for(let entry of entries2){if(visited>=GREP_MAX_FILES)return;let fullPath=path294.join(dir,entry.name),relPath=path294.relative(directory,fullPath).replace(/\\/g,"/");if(entry.isDirectory()){if(!GREP_SKIP_DIRECTORIES.has(entry.name))walk(fullPath);continue}if(!entry.isFile())continue;if(visited++,!matcher(relPath))continue;try{if(statSync89(fullPath).size>GREP_MAX_BYTES_PER_FILE)continue;let found=readFileSync128(fullPath,"utf-8").match(pattern);if(found)matches+=found.length}catch{}}};if(walk(directory),visited>=GREP_MAX_FILES)return{result:"error",detail:`grep: file scan exceeded ${GREP_MAX_FILES} files`};if(matches===0)return{result:"pass",detail:"grep: zero matches"};return{result:"fail",detail:`grep: ${matches} match(es) found`}}async function runToolPredicate(rest,directory){let raw=rest.trim();if(!raw)return{result:"error",detail:"tool: empty command"};if(raw.includes("\x00"))return{result:"error",detail:"tool: null byte in command"};let argvParts=raw.split(/\s+/).filter((p)=>p.length>0);if(argvParts.length===0)return{result:"error",detail:"tool: empty command"};let binary=argvParts[0];if(binary.includes("/")||binary.includes("\\"))return{result:"error",detail:`tool: path-qualified binary "${binary}" is not allowed`};if(!TOOL_BINARY_ALLOWLIST.has(binary))return{result:"error",detail:`tool: binary "${binary}" is not on the allowlist`};let resolved=findBinaryInPath(binary);if(!resolved)return{result:"error",detail:`tool: binary "${binary}" not found`};let res=await runArgv([resolved,...argvParts.slice(1)],directory);if(res.timedOut)return{result:"error",detail:"tool: timed out"};if(res.exitCode===0)return{result:"pass",detail:"tool: exit 0"};return{result:"fail",detail:`tool: exit ${res.exitCode} ${res.stderr.slice(0,200)}`}}async function changedPaths(directory){let git2=findBinaryInPath("git");if(!git2)return null;let res=await runArgv([git2,"status","--porcelain","-z"],directory);if(res.timedOut||res.exitCode!==0)return null;let out=new Set;for(let entry of res.stdout.split("\x00")){if(entry.length<=3)continue;let p=entry.slice(3);if(p)out.add(path294.normalize(p))}return out}async function runFileModifiedPredicate(rest,directory,expectModified){let label=expectModified?"file_modified":"file_not_modified",safe2=validateRepoRelativeGlob(directory,rest);if(safe2===null)return{result:"error",detail:`${label}: unsafe or empty path "${rest}"`};let changed2=await changedPaths(directory);if(changed2===null)return{result:"error",detail:`${label}: git unavailable or failed`};let target=path294.normalize(safe2),isChanged=changed2.has(target);return{result:(expectModified?isChanged:!isChanged)?"pass":"fail",detail:`${label}: ${target} ${isChanged?"changed":"unchanged"}`}}async function runDirectivePredicate(predicate,directory){try{if(typeof predicate!=="string"||!predicate.trim())return{result:"error",detail:"predicate: empty"};let trimmed=predicate.trim(),firstColon=trimmed.indexOf(":");if(firstColon<=0)return{result:"error",detail:"predicate: missing handler prefix (expected <handler>:...)"};let handler=trimmed.slice(0,firstColon),rest=trimmed.slice(firstColon+1);switch(handler){case"grep":return await runGrepPredicate(rest,directory);case"tool":return await runToolPredicate(rest,directory);case"file_not_modified":return await runFileModifiedPredicate(rest,directory,!1);case"file_modified":return await runFileModifiedPredicate(rest,directory,!0);default:return{result:"error",detail:`predicate: unknown handler "${handler}"`}}}catch(err){return warn(`[directive-predicate-runner] unexpected error: ${err instanceof Error?err.message:String(err)}`),{result:"error",detail:"predicate: unexpected error (fail-closed)"}}}var import_picomatch2,PREDICATE_TIMEOUT_MS=15000,GREP_MAX_FILES=1e4,GREP_MAX_BYTES_PER_FILE=1e6,GREP_SKIP_DIRECTORIES,TOOL_BINARY_ALLOWLIST;var init_directive_predicate_runner=__esm(()=>{init_bun_compat();init_logger();import_picomatch2=__toESM(require_picomatch2(),1),GREP_SKIP_DIRECTORIES=new Set([".git",".swarm","node_modules","dist","coverage"]),TOOL_BINARY_ALLOWLIST=new Set(["rg","grep","git","biome","eslint","tsc","ruff"])});function parseReviewerDirectiveCompliance(text){if(!text||typeof text!=="string")return[];let out=[];for(let m of text.matchAll(VERDICT_PATTERN)){let verb=m[1].toUpperCase(),traceId=decodeDirectiveCorrelationId(m[2]),entryId=decodeDirectiveCorrelationId(m[3]);if(!traceId||!entryId)continue;let evidence2=m[4]?.trim().slice(0,280),verdict=verb==="VERIFIED"?"verified":verb==="VIOLATED"?"violated":"n_a";out.push({trace_id:traceId,entry_id:entryId,verdict,evidence:evidence2})}return out}function verdictToEventType(v){return v==="verified"?"applied":v==="violated"?"violated":"n_a"}function pairKey2(traceId,entryId){return JSON.stringify([traceId,entryId])}async function reconcileReviewerVerdicts(params){let result={emitted:[],omittedCriticals:[],uncertainties:[]},verifyByPair=new Map(params.directivesToVerify.map((d)=>[pairKey2(d.trace_id,d.entry_id),d]));if(verifyByPair.size===0)return result;let verdictsByPair=new Map;for(let verdict of parseReviewerDirectiveCompliance(params.transcript)){let key2=pairKey2(verdict.trace_id,verdict.entry_id);if(!verifyByPair.has(key2))continue;let existing=verdictsByPair.get(key2)??[];existing.push(verdict),verdictsByPair.set(key2,existing)}let pending=[];for(let[key2,directive]of verifyByPair){let matching=verdictsByPair.get(key2)??[];if(matching.length>1){result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"duplicate_verdict",uncertainty:"Reviewer emitted more than one verdict for the exact pair"});continue}if(matching.length===0){if(directive.priority!=="critical")continue;result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_omitted"});continue}let verdict=matching[0];if(verdict.verdict==="verified"&&!verdict.evidence?.trim()){if(result.uncertainties.push({trace_id:directive.trace_id,entry_id:directive.entry_id,code:"reviewer_missing_evidence",uncertainty:"VERIFIED requires nonempty evidence"}),directive.priority==="critical")result.omittedCriticals.push({trace_id:directive.trace_id,entry_id:directive.entry_id}),pending.push({directive,type:"violated",reason:"reviewer_missing_evidence"});continue}let item={directive,type:verdictToEventType(verdict.verdict),reason:verdict.evidence};if(verdict.verdict==="violated"&&directive.verification_predicate)try{let outcome=await _internals240.runDirectivePredicate(directive.verification_predicate,params.directory);item.predicate_check={predicate:directive.verification_predicate,result:outcome.result,detail:outcome.detail}}catch(error93){item.predicate_check={predicate:directive.verification_predicate,result:"error",detail:error93 instanceof Error?error93.message:String(error93)}}pending.push(item)}let groups=new Map;for(let item of pending){let groupKey=JSON.stringify([item.directive.trace_id,item.directive.session_id,item.directive.cohort_id,item.directive.source_link_id,item.directive.prior_terminal_outcome,item.directive.prior_terminal_event_id]),group=groups.get(groupKey)??[];group.push(item),groups.set(groupKey,group)}let violatedIds=new Set,agent=params.agent??"reviewer";for(let group of groups.values()){let first=group[0].directive,remediationAuthorization=(first.prior_terminal_outcome==="violated"||first.prior_terminal_outcome==="contradicted")&&first.prior_terminal_event_id&&group.some((item)=>item.type!=="violated")?{actor:"reviewer-remediation",reason:"reviewer_verified_remediation",expected_event_id:first.prior_terminal_event_id,expected_outcome:first.prior_terminal_outcome}:void 0,committedEntries;try{let committed=await _internals240.validateAndCommitTerminalBatch(params.directory,{trace_id:first.trace_id,session_id:first.session_id,cohort_id:first.cohort_id,source_link_id:first.source_link_id,authorization:remediationAuthorization,items:group.map((item)=>({entry_id:item.directive.entry_id,outcome:item.type,source:"reviewer",reason:item.reason}))});if(!committed.ok){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:committed.code,uncertainty:committed.detail});continue}committedEntries=new Set(committed.accepted.map((terminal)=>terminal.entry_id));for(let rejected2 of committed.rejected)result.uncertainties.push({trace_id:first.trace_id,entry_id:rejected2.entry_id||void 0,code:rejected2.reason,uncertainty:"Authoritative ledger rejected reviewer terminal"})}catch(error93){for(let item of group)result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"ledger_exception",uncertainty:error93 instanceof Error?error93.message:String(error93)});continue}for(let item of group){if(!committedEntries.has(item.directive.entry_id))continue;try{if(await _internals240.recordKnowledgeEvent(params.directory,{type:item.type,trace_id:item.directive.trace_id,knowledge_id:item.directive.entry_id,session_id:item.directive.session_id,task_id:params.taskId,phase:params.phase,agent,source:"reviewer",reason:item.reason,predicate_check:item.predicate_check}),result.emitted.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,id:item.directive.entry_id,type:item.type,source:"reviewer"}),item.type==="violated")violatedIds.add(item.directive.entry_id)}catch(error93){result.uncertainties.push({trace_id:item.directive.trace_id,entry_id:item.directive.entry_id,code:"diagnostic_event_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}}}if(violatedIds.size>0)try{await _internals240.escalateViolatedEntries(params.directory,[...violatedIds])}catch(error93){result.uncertainties.push({trace_id:"",code:"escalation_failed",uncertainty:error93 instanceof Error?error93.message:String(error93)})}return result}function isTaskTool7(tool3){return tool3==="Task"||tool3==="task"}async function collectReviewerVerdictsAfter(directory,input,output){if(!isTaskTool7(input.tool))return;let parsedArgs=parseDelegationArgs(input.args);if(!parsedArgs)return;if(stripKnownSwarmPrefix(parsedArgs.targetAgent).toLowerCase()!=="reviewer")return;let argsRecord=input.args&&typeof input.args==="object"?input.args:null,prompt=argsRecord&&typeof argsRecord.prompt==="string"?argsRecord.prompt:"";if(!prompt)return;let transcript=typeof output.output==="string"?output.output:"";if(!transcript)return;let directivesToVerify=parseDirectivesToVerifyBlock(prompt);if(directivesToVerify.length===0)return;let sessionId=typeof input.sessionID==="string"?input.sessionID:void 0;await reconcileReviewerVerdicts({directory,transcript,directivesToVerify,sessionId,agent:"reviewer"})}var _internals240,VERDICT_PATTERN;var init_reviewer_verdict_parser=__esm(()=>{init_reviewer_directive_compliance();init_schema();init_directive_predicate_runner();init_knowledge_escalator();init_knowledge_events();init_knowledge_receipt_ledger();init_skill_propagation_gate();_internals240={validateAndCommitTerminalBatch,recordKnowledgeEvent,runDirectivePredicate,escalateViolatedEntries},VERDICT_PATTERN=/\b(VERIFIED|VIOLATED|N\/A)\s*:\s*([^:\s]{1,512})\s*:\s*([^:\s]{1,512})(?:\s+(?:evidence|reason)\s*=\s*([^\n\r]+?))?(?=$|[\n\r]|\s+(?:VERIFIED|VIOLATED|N\/A)\b)/gi});import{createHash as createHash101}from"node:crypto";function delegationCostRecordMaterial(record3){if(!record3.laneId)return`${record3.parentSessionId}\x00${record3.callID}`;return`${record3.parentSessionId}\x00${record3.callID}\x00lane:${record3.laneId}`}function buildDelegationTerminalIdentityFields(input){let material=delegationCostRecordMaterial(input.record);return{record_id:createHash101("sha256").update(`delegation-cost-id-v1\x00${material}`).digest("hex").slice(0,32),identity_fingerprint:createHash101("sha256").update(`delegation-cost-identity-v1\x00${material}\x00${input.record.swarmPrefixedAgent}\x00${input.model??""}`).digest("hex").slice(0,32),version:1,parent_session_digest:createHash101("sha256").update(`delegation-cost-parent-v1\x00${input.record.parentSessionId}`).digest("hex").slice(0,32),child_session_digest:createHash101("sha256").update(`delegation-cost-child-v1\x00${input.record.subagentSessionId}`).digest("hex").slice(0,32),...input.recovered?{recovered:!0}:{}}}var init_delegation_cost_identity=()=>{};var exports_delegation_lifecycle={};__export(exports_delegation_lifecycle,{settleDelegationTerminal:()=>settleDelegationTerminal,recoverTerminalLaneReceipts:()=>recoverTerminalLaneReceipts,isBenignSettleOutcome:()=>isBenignSettleOutcome,emitDelegationEventlessTerminalEnd:()=>emitDelegationEventlessTerminalEnd,emitDelegationBegin:()=>emitDelegationBegin,delegationCostRecordMaterial:()=>delegationCostRecordMaterial,buildDelegationTerminal:()=>buildDelegationTerminal,_internals:()=>_internals259,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS:()=>TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,MAX_TERMINAL_LANE_RECEIPT_RECOVERY:()=>MAX_TERMINAL_LANE_RECEIPT_RECOVERY});import*as fs183 from"node:fs";import*as path315 from"node:path";function isBenignSettleOutcome(kind){return kind==="duplicate"||kind==="conflict"||kind==="already_terminal_without_event"}function buildDelegationTerminal(record3,terminal,now2){return{eventId:buildBackgroundCompletionEventId({correlationId:record3.correlationId,jobId:record3.jobId,status:terminal.status,resultDigest:terminal.result.digest}),status:terminal.status,recordedAt:now2,result:terminal.result}}async function settleDelegationTerminal(directory,record3,terminal,observations={},now2=Date.now()){let claim=await _internals259.claimTerminalResult(directory,record3.correlationId,buildDelegationTerminal(record3,terminal,now2));if(claim){if(claim.disposition==="claimed")return await runDelegationTerminalObservations(directory,claim.record,terminal,observations,now2),{kind:"claimed",record:claim.record};if(claim.disposition==="duplicate"&&observations.transcript)await reconcileLaneKnowledgeReceipts(directory,claim.record,observations,!0);return{kind:"duplicate",record:claim.record}}let reread=_internals259.findByCorrelationIdDetailed(directory,record3.correlationId);if(reread.status==="uncertain")return{kind:"uncertain",reason:reread.reason};if(!reread.value)return{kind:"missing"};if(isTerminalDelegationStatus(reread.value.status)){if(reread.value.terminalResult)return{kind:"conflict",record:reread.value};return emitDelegationEventlessTerminalEnd(reread.value,reread.value.status),{kind:"already_terminal_without_event",record:reread.value}}return{kind:"not_open",record:reread.value}}function emitDelegationBegin(record3){try{_internals259.telemetry.delegationBegin(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??""),recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},attemptClass:"attempt",outcomeStatus:"unknown"})}catch{}}function terminalAttemptClass(status2){if(status2==="cancelled")return"cancelled";return"result"}function terminalAttemptOutcome(status2){if(status2==="completed")return"success";if(status2==="error"||status2==="failed")return"failure";return"unknown"}function emitDelegationCostObservation(record3,observations,terminalStatus,recovered=!1){try{let costFields=buildDelegationCostFields({raw:observations.costRaw,model:observations.model,pricing:observations.pricing});Object.assign(costFields,buildDelegationTerminalIdentityFields({record:record3,model:observations.model,recovered})),_internals259.telemetry.delegationEnd(record3.parentSessionId,record3.swarmPrefixedAgent,record3.planTaskId??"",terminalStatus,costFields);let usageAttested=costFields.cost_source==="reported";recordExecutionAttempt({sessionId:record3.parentSessionId,...record3.planTaskId?{taskId:record3.planTaskId}:{},...record3.callID?{callId:record3.callID}:{},...record3.laneId?{laneId:record3.laneId}:{},attemptClass:terminalAttemptClass(terminalStatus),outcomeStatus:terminalAttemptOutcome(terminalStatus),cost:{...observations.startedAt!==void 0?{latencyMs:Math.max(0,Date.now()-observations.startedAt)}:{},...usageAttested?{inputTokens:costFields.tokens_input,outputTokens:costFields.tokens_output,cacheReadTokens:costFields.tokens_cache}:{},...costFields.cost_source==="reported"&&costFields.cost_usd!==null?{billedCostUsd:costFields.cost_usd}:{},...costFields.cost_source==="estimated"&&costFields.cost_usd!==null?{estimatedCostUsd:costFields.cost_usd}:{}}})}catch(error93){log(`[delegation-lifecycle] cost observation skipped: ${error93 instanceof Error?error93.message:String(error93)}`)}}function emitDelegationEventlessTerminalEnd(record3,terminalStatus){emitDelegationCostObservation(record3,{},terminalStatus,!0)}async function appendDelegationTrajectoryObservation(directory,record3,terminalStatus,observations,now2){try{let lastStep=await getCurrentStep(record3.parentSessionId,directory);seedTrajectoryStepCounter(record3.parentSessionId,directory,lastStep);let entry={step:nextTrajectoryStep(record3.parentSessionId,directory),agent:record3.swarmPrefixedAgent,action:"delegate",target:record3.laneId??record3.correlationId,intent:`dispatch_lanes terminal ${terminalStatus}`,timestamp:new Date(now2).toISOString(),result:terminalStatus==="completed"?"success":"failure",tool:"dispatch_lanes",...observations.startedAt!==void 0?{elapsed_ms:Math.max(0,now2-observations.startedAt)}:{},...record3.batchId!==void 0?{batchId:record3.batchId}:{},laneId:record3.laneId??record3.correlationId,...record3.planTaskId?{taskId:record3.planTaskId}:{}};await appendTrajectoryEntry(record3.parentSessionId,entry,directory)}catch{}}async function reconcileLaneKnowledgeReceipts(directory,record3,observations,replay=!1){if(!observations.transcript)return;try{let ack=await collectLaneDelegateAcks({directory,sessionId:record3.subagentSessionId,agent:record3.swarmPrefixedAgent,transcript:observations.transcript,replay});if(record3.normalizedAgent!=="reviewer")return;let phase=ack.phases.find((value)=>Boolean(value));if(!phase)return;let directivesToVerify=await readPhaseDirectivesToVerify(directory,phase);if(directivesToVerify.length===0)return;await reconcileReviewerVerdicts({directory,transcript:observations.transcript,directivesToVerify,sessionId:record3.subagentSessionId,agent:"reviewer"})}catch{}}async function runDelegationTerminalObservations(directory,record3,terminal,observations,now2){emitDelegationCostObservation(record3,observations,terminal.status),await appendDelegationTrajectoryObservation(directory,record3,terminal.status,observations,now2),await reconcileLaneKnowledgeReceipts(directory,record3,observations)}function candidateAfter(record3,cursor){if(record3.updatedAt!==cursor.updatedAt)return record3.updatedAt>cursor.updatedAt;return record3.correlationId>cursor.correlationId}function readRecoveryCursor(directory){try{let filePath=path315.join(directory,".swarm",RECOVERY_CURSOR_FILE);if(!fs183.existsSync(filePath))return null;let parsed=JSON.parse(fs183.readFileSync(filePath,"utf-8"));if(typeof parsed.updatedAt==="number"&&Number.isFinite(parsed.updatedAt)&&typeof parsed.correlationId==="string"&&parsed.correlationId.length>0)return{updatedAt:parsed.updatedAt,correlationId:parsed.correlationId};return null}catch{return null}}function writeRecoveryCursor(directory,cursor){try{let swarmDir=path315.join(directory,".swarm");fs183.mkdirSync(swarmDir,{recursive:!0});let filePath=path315.join(swarmDir,RECOVERY_CURSOR_FILE);if(cursor===null)fs183.rmSync(filePath,{force:!0});else fs183.writeFileSync(filePath,JSON.stringify(cursor),"utf-8")}catch{}}function isRecoverableTerminalLaneRecord(record3){return Boolean(record3.laneId&&record3.terminalResult&&typeof record3.terminalResult.result.text==="string"&&record3.terminalResult.result.text.length>0)}async function recoverTerminalLaneReceipts(directory,records,options={}){let now2=options.now??Date.now,deadlineMs=options.deadlineMs??TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS,deadline=now2()+deadlineMs;if(records!==void 0){let recovered2=0;for(let record3 of records){if(!isRecoverableTerminalLaneRecord(record3))continue;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;if(now2()>=deadline)return{recovered:recovered2,exhaustedBudget:!0};try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered2+=1}catch{}}return{recovered:recovered2,exhaustedBudget:!1}}let enumeration=readDelegationsDetailed(directory);if(enumeration.status==="uncertain")return warn(`[delegation-lifecycle] terminal-lane receipt recovery deferred: delegation store unreadable after ${enumeration.attempts} attempts (${enumeration.reason})`),{recovered:0,exhaustedBudget:!1};let candidates=enumeration.records.filter(isRecoverableTerminalLaneRecord).sort((left,right)=>{if(left.updatedAt!==right.updatedAt)return left.updatedAt-right.updatedAt;return left.correlationId<right.correlationId?-1:left.correlationId>right.correlationId?1:0});if(candidates.length===0)return{recovered:0,exhaustedBudget:!1};let cursor=readRecoveryCursor(directory),selected=cursor?candidates.filter((record3)=>candidateAfter(record3,cursor)):candidates,wrapped=!1;if(selected.length===0)selected=candidates,wrapped=!0;let recovered=0,lastProcessed=null;for(let record3 of selected){if(recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)break;if(now2()>=deadline)break;let transcript=record3.terminalResult?.result.text;if(!transcript)continue;try{await reconcileLaneKnowledgeReceipts(directory,record3,{transcript},!0),recovered+=1,lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}catch{lastProcessed={updatedAt:record3.updatedAt,correlationId:record3.correlationId}}}let lastCandidate=selected[selected.length-1],processedAll=selected.length>0&&lastProcessed!==null&&lastCandidate!==void 0&&lastProcessed.updatedAt===lastCandidate.updatedAt&&lastProcessed.correlationId===lastCandidate.correlationId,nextCursor=wrapped&&processedAll?null:lastProcessed??cursor??null;if(nextCursor?.correlationId!==cursor?.correlationId)writeRecoveryCursor(directory,nextCursor);return{recovered,exhaustedBudget:recovered<selected.length&&(now2()>=deadline||recovered>=MAX_TERMINAL_LANE_RECEIPT_RECOVERY)}}var MAX_TERMINAL_LANE_RECEIPT_RECOVERY=64,TERMINAL_LANE_RECEIPT_RECOVERY_DEADLINE_MS=5000,RECOVERY_CURSOR_FILE="lane-receipt-recovery-cursor.json",_internals259;var init_delegation_lifecycle=__esm(()=>{init_delegate_ack_collector();init_phase_directives();init_reviewer_verdict_parser();init_trajectory_step_state();init_trajectory_store();init_cost_accounting();init_execution_attempt();init_telemetry();init_logger();init_delegation_cost_identity();init_pending_delegations();init_delegation_cost_identity();registerStaleSweepObserver((record3)=>{emitDelegationEventlessTerminalEnd(record3,"stale")});_internals259={claimTerminalResult,findByCorrelationId,findByCorrelationIdDetailed,telemetry}});var exports_design_doc_drift={};__export(exports_design_doc_drift,{runDesignDocDriftCheck:()=>runDesignDocDriftCheck,_internals:()=>_internals281});import*as fs204 from"node:fs";import*as path339 from"node:path";function mtimeMsOrNull(absPath){try{return fs204.statSync(absPath).mtimeMs}catch{return null}}function resolveAnchorWithin(directory,anchor){if(!anchor||typeof anchor!=="string")return null;let root=path339.resolve(directory),resolved=path339.resolve(root,anchor),rel3=path339.relative(root,resolved);if(rel3.startsWith("..")||path339.isAbsolute(rel3))return null;return resolved}async function runDesignDocDriftCheck(directory,phase,outDir){try{let root=path339.resolve(directory),outAbs=path339.resolve(root,outDir),outRel=path339.relative(root,outAbs);if(outRel.startsWith("..")||path339.isAbsolute(outRel))return null;let docMtimes=new Map,checkedDocs=[],missingDocs=[];for(let[docName,relFile]of Object.entries(DESIGN_DOC_FILES)){let abs=path339.join(outAbs,relFile),mtime=mtimeMsOrNull(abs);if(docMtimes.set(docName,mtime),mtime===null)missingDocs.push(path339.join(outDir,relFile));else checkedDocs.push(path339.join(outDir,relFile))}let traceabilityAbs=path339.join(outAbs,TRACEABILITY_REL),registry4=null;try{if((await fs204.promises.stat(traceabilityAbs)).size<=MAX_TRACEABILITY_BYTES){let raw=await fs204.promises.readFile(traceabilityAbs,"utf-8"),parsed=JSON.parse(raw);registry4=parsed&&typeof parsed==="object"&&!Array.isArray(parsed)?parsed:null}}catch{registry4=null}let noDocs=checkedDocs.length===0||registry4===null,effectiveSpec=readEffectiveSpecSync(root),specMtime=effectiveSpec?.mtime?Date.parse(effectiveSpec.mtime):null,staleSections=[];if(!noDocs&&Array.isArray(registry4?.sections))for(let section of registry4.sections){if(!section||typeof section.section_id!=="string")continue;if(typeof section.doc!=="string"||!docMtimes.has(section.doc))continue;let docMtime=docMtimes.get(section.doc)??null;if(docMtime===null){staleSections.push({section_id:section.section_id,doc:section.doc,reason:"owning design doc is missing"});continue}let flagged=!1;for(let anchor of section.code_anchors??[]){let anchorAbs=resolveAnchorWithin(directory,anchor);if(anchorAbs===null)continue;let anchorMtime=mtimeMsOrNull(anchorAbs);if(anchorMtime!==null&&anchorMtime>docMtime){staleSections.push({section_id:section.section_id,doc:section.doc,reason:`code anchor ${anchor} changed after the doc`}),flagged=!0;break}}if(!flagged&&specMtime!==null&&specMtime>docMtime&&(section.spec_frs?.length??0)>0)staleSections.push({section_id:section.section_id,doc:section.doc,reason:"effective spec changed after the doc"})}let verdict=noDocs?"NO_DOCS":staleSections.length>0?"DOC_STALE":"DOC_FRESH",report={schema_version:1,phase,timestamp:new Date().toISOString(),out_dir:outDir,verdict,stale_sections:staleSections,missing_docs:missingDocs,checked_docs:checkedDocs},locator=phaseReportLocator("design_doc_drift",phase);return await upsertPhaseReportDb(directory,"design_doc_drift",phase,JSON.stringify(report,null,2)),getGlobalEventBus().publish("curator.docdrift.completed",{phase,verdict,stale_count:staleSections.length,report_path:locator}),report}catch(err){try{getGlobalEventBus().publish("curator.error",{operation:"docdrift",phase,error:String(err)})}catch{}return warn(`[design-doc-drift] check failed for phase ${phase}: ${String(err)}`),null}}var MAX_TRACEABILITY_BYTES=1048576,DESIGN_DOC_FILES,TRACEABILITY_REL,_internals281;var init_design_doc_drift=__esm(()=>{init_event_bus();init_phase_report_store();init_effective_spec();init_logger();DESIGN_DOC_FILES={domain:"domain.md","technical-spec":"technical-spec.md","behavior-spec":"behavior-spec.md","reference-impl":path339.join("reference","reference-impl.md"),"idiom-notes":path339.join("reference","idiom-notes.md")},TRACEABILITY_REL=path339.join("reference","traceability.json");_internals281={mtimeMsOrNull,resolveAnchorWithin,DESIGN_DOC_FILES}});var exports_project_context={};__export(exports_project_context,{buildProjectContext:()=>buildProjectContext,_internals:()=>_internals314,LANG_BACKEND_DETECTION_TIMEOUT_MS:()=>LANG_BACKEND_DETECTION_TIMEOUT_MS});import*as fs238 from"node:fs";import*as path382 from"node:path";function detectFileExists2(directory,pattern){if(pattern.includes("*")||pattern.includes("?"))try{let files=fs238.readdirSync(directory),regex=new RegExp(`^${pattern.replace(/\./g,"\\.").replace(/\*/g,".*").replace(/\?/g,".")}$`);return files.some((f)=>regex.test(f))}catch{return!1}try{return fs238.accessSync(path382.join(directory,pattern)),!0}catch{return!1}}function selectTestCommandFromScriptsTest(backend,directory){let pkgRaw;try{pkgRaw=fs238.readFileSync(path382.join(directory,"package.json"),"utf-8")}catch{return null}let pkg;try{pkg=JSON.parse(pkgRaw)}catch{return null}let script=pkg.scripts?.test;if(!script)return null;let fwName=null;if(script.includes("vitest"))fwName="vitest";else if(script.includes("jest"))fwName="jest";else if(script.includes("mocha"))fwName="mocha";else if(script.includes("bun test"))fwName="bun:test";if(!fwName)return null;let fw=backend.test.frameworks.find((f)=>f.name===fwName);return fw?fw.cmd:null}function selectTestCommandFast(backend,directory){let fromScripts=selectTestCommandFromScriptsTest(backend,directory);if(fromScripts!==null)return fromScripts;let sorted2=[...backend.test.frameworks].sort((a,b)=>b.priority-a.priority);for(let fw of sorted2){if(!detectFileExists2(directory,fw.detect))continue;return fw.cmd}return null}function selectBuildCommandFast(backend,directory){let sorted2=[...backend.build.commands].sort((a,b)=>b.priority-a.priority);for(let cmd of sorted2){if(cmd.detectFile&&!detectFileExists2(directory,cmd.detectFile))continue;return cmd.cmd}return null}function selectLintCommand(backend,directory){let sorted2=[...backend.lint.linters].sort((a,b)=>b.priority-a.priority);for(let lint2 of sorted2){if(!detectFileExists2(directory,lint2.detect))continue;return lint2.cmd}return null}async function buildProjectContext(directory,signal2){let backend=await _internals314.pickBackend(directory,signal2);if(!backend)return null;let profiles=_internals314.pickedProfiles(directory),ctx=emptyProjectContext();ctx.PROJECT_LANGUAGE=backend.displayName;let buildCmd=selectBuildCommandFast(backend,directory);if(buildCmd)ctx.BUILD_CMD=buildCmd;let testCmd=selectTestCommandFast(backend,directory);if(testCmd)ctx.TEST_CMD=testCmd;let lintCmd=selectLintCommand(backend,directory);if(lintCmd)ctx.LINT_CMD=lintCmd;if(backend.id==="php"){let overlay=getLaravelCommandOverlay(directory);if(overlay){if(ctx.TEST_CMD=overlay.testCommand,overlay.lintCommand)ctx.LINT_CMD=overlay.lintCommand}}let[frameworkSel,entryPoints]=await Promise.all([backend.selectFramework?backend.selectFramework(directory).catch(()=>null):Promise.resolve(null),backend.selectEntryPoints?backend.selectEntryPoints(directory).catch(()=>[]):Promise.resolve([])]);if(frameworkSel)ctx.PROJECT_FRAMEWORK=frameworkSel.name;if(entryPoints.length>0)ctx.ENTRY_POINTS=entryPoints.join(", ");if(backend.prompts.coderConstraints.length>0)ctx.CODER_CONSTRAINTS=bulletList(backend.prompts.coderConstraints);if(backend.prompts.testConstraints&&backend.prompts.testConstraints.length>0)ctx.TEST_CONSTRAINTS=bulletList(backend.prompts.testConstraints);if(backend.prompts.reviewerChecklist.length>0)ctx.REVIEWER_CHECKLIST=bulletList(backend.prompts.reviewerChecklist);if(profiles.length>1)ctx.PROJECT_CONTEXT_SECONDARY_LANGUAGES=profiles.slice(1).map((p)=>p.id).join(", ");return ctx}var LANG_BACKEND_DETECTION_TIMEOUT_MS=300,_internals314;var init_project_context=__esm(()=>{init_dispatch();init_framework_detector();_internals314={pickBackend,pickedProfiles}});init_package();init_agents2();init_critic();import{createHash as createHash116}from"node:crypto";import{mkdirSync as mkdirSync101,writeFileSync as writeFileSync66}from"node:fs";import*as path383 from"node:path";import{performance as performance2}from"node:perf_hooks";import{fileURLToPath as fileURLToPath7}from"node:url";init_event_bus();init_evidence_summary_integration();init_manager4();init_manager();init_utils();import*as fs149 from"node:fs";import*as path271 from"node:path";class PlanSyncWorker{directory;debounceMs;pollIntervalMs;syncTimeoutMs;onSyncComplete;status="stopped";watcher=null;pollTimer=null;debounceTimer=null;syncing=!1;pendingSync=!1;lastStat=null;disposed=!1;constructor(options={}){this.directory=options.directory??"",this.debounceMs=options.debounceMs??500,this.pollIntervalMs=options.pollIntervalMs??2000,this.syncTimeoutMs=options.syncTimeoutMs??30000,this.onSyncComplete=options.onSyncComplete}getSwarmDir(){return path271.resolve(this.directory,".swarm")}getPlanJsonPath(){return path271.join(this.getSwarmDir(),"plan.json")}start(){if(this.disposed){log("[PlanSyncWorker] Cannot start - worker has been disposed");return}if(!this.directory){log("[PlanSyncWorker] Cannot start - no directory provided");return}if(this.status==="running"||this.status==="starting"){log("[PlanSyncWorker] Already running or starting");return}this.status="starting",log("[PlanSyncWorker] Starting..."),this.initializeStat(),this.setupPolling(),this.setupNativeWatcher(),this.status="running",log("[PlanSyncWorker] Started watching for plan.json changes")}stop(){if(this.status==="stopped"||this.status==="stopping")return;if(this.status="stopping",log("[PlanSyncWorker] Stopping..."),this.clearDebounce(),this.watcher)this.watcher.close(),this.watcher=null;if(this.pollTimer)clearInterval(this.pollTimer),this.pollTimer=null;this.status="stopped",log("[PlanSyncWorker] Stopped")}dispose(){this.stop(),this.disposed=!0,this.lastStat=null,log("[PlanSyncWorker] Disposed")}getStatus(){return this.status}isRunning(){return this.status==="running"}initializeStat(){try{let stats2=fs149.statSync(this.getPlanJsonPath());this.lastStat={mtimeMs:stats2.mtimeMs,size:stats2.size}}catch{this.lastStat=null}}setupNativeWatcher(){let swarmDir=this.getSwarmDir();try{if(!fs149.existsSync(swarmDir))return log("[PlanSyncWorker] Swarm directory does not exist yet"),!1;return this.watcher=fs149.watch(swarmDir,{persistent:!1},(_eventType,filename)=>{if(this.disposed||this.status!=="running")return;if(filename&&(filename.includes(".tmp.")||filename.endsWith(".rebuild")))return;if(filename==="plan.json"||filename===void 0)this.debouncedSync()}),this.watcher.on("error",(error93)=>{if(this.disposed||this.status!=="running")return;if(log("[PlanSyncWorker] Watcher error, falling back to polling",{error:error93.message}),this.watcher)this.watcher.close(),this.watcher=null;this.setupPolling()}),log("[PlanSyncWorker] Native fs.watch established"),!0}catch(error93){return log("[PlanSyncWorker] Failed to setup native watcher",{error:error93 instanceof Error?error93.message:String(error93)}),!1}}setupPolling(){if(this.pollTimer)clearInterval(this.pollTimer);if(this.pollTimer=setInterval(()=>{if(this.disposed||this.status!=="running")return;this.pollCheck()},this.pollIntervalMs),typeof this.pollTimer.unref==="function")this.pollTimer.unref();log("[PlanSyncWorker] Polling fallback established",{intervalMs:this.pollIntervalMs})}pollCheck(){try{let planPath=this.getPlanJsonPath();if(!fs149.existsSync(planPath)){if(this.lastStat!==null)this.lastStat=null,log("[PlanSyncWorker] plan.json deleted");return}let stats2=fs149.statSync(planPath),currentStat={mtimeMs:stats2.mtimeMs,size:stats2.size};if(this.lastStat===null||currentStat.mtimeMs!==this.lastStat.mtimeMs||currentStat.size!==this.lastStat.size)this.lastStat=currentStat,this.debouncedSync()}catch(error93){log("[PlanSyncWorker] Poll check error",{error:error93 instanceof Error?error93.message:String(error93)})}}debouncedSync(){if(this.disposed||this.status!=="running")return;if(this.debounceTimer)clearTimeout(this.debounceTimer);this.debounceTimer=setTimeout(()=>{if(this.disposed||this.status!=="running")return;this.debounceTimer=null,this.triggerSync()},this.debounceMs)}clearDebounce(){if(this.debounceTimer)clearTimeout(this.debounceTimer),this.debounceTimer=null}triggerSync(){if(this.syncing){this.pendingSync=!0,log("[PlanSyncWorker] Sync pending (in-flight)");return}this.executeSync()}async executeSync(){this.syncing=!0;try{log("[PlanSyncWorker] Syncing plan..."),this.checkForUnauthorizedWrite();let plan=await this.withTimeout(_internals53.loadPlanJsonOnly(this.directory),this.syncTimeoutMs,"Sync operation timed out");if(plan&&plan.phases.length>0)await _internals53.regeneratePlanMarkdown(this.directory,plan),log("[PlanSyncWorker] Sync complete",{title:plan.title,phase:plan.current_phase}),this.safeCallback(!0);else if(plan)log("[PlanSyncWorker] Plan has no phases, skipping markdown regeneration"),this.safeCallback(!0);else log("[PlanSyncWorker] No plan found to sync"),this.safeCallback(!0)}catch(error93){if(error93 instanceof Error&&error93.message.includes("timed out"))log("[PlanSyncWorker] Sync timed out after "+this.syncTimeoutMs+"ms, worker remains active");else log("[PlanSyncWorker] Sync failed",{error:error93 instanceof Error?error93.message:String(error93)});this.safeCallback(!1,error93 instanceof Error?error93:Error(String(error93)))}finally{if(this.syncing=!1,this.pendingSync&&!this.disposed&&this.status==="running")this.pendingSync=!1,log("[PlanSyncWorker] Executing pending sync"),this.executeSync()}}safeCallback(success3,error93){if(this.onSyncComplete)try{this.onSyncComplete(success3,error93)}catch(callbackError){log("[PlanSyncWorker] onSyncComplete callback threw error (ignored)",{callbackError:callbackError instanceof Error?callbackError.message:String(callbackError)})}}checkForUnauthorizedWrite(){try{let swarmDir=this.getSwarmDir(),planJsonPath=path271.join(swarmDir,"plan.json"),markerPath=path271.join(swarmDir,".plan-write-marker"),planStats=fs149.statSync(planJsonPath),planMtimeMs=Math.floor(planStats.mtimeMs),markerContent=fs149.readFileSync(markerPath,"utf8"),marker=JSON.parse(markerContent);if(marker.in_progress===!0){log("[PlanSyncWorker] Skipping unauthorized-write check - plan write in progress");return}let markerTimestampMs=new Date(marker.timestamp).getTime();if(planMtimeMs>markerTimestampMs+5000)log("[PlanSyncWorker] WARNING: plan.json may have been written outside save_plan/savePlan - unauthorized direct write suspected",{planMtimeMs,markerTimestampMs})}catch{}}withTimeout(promise3,ms,timeoutMessage2){return new Promise((resolve106,reject)=>{let timer=setTimeout(()=>{reject(Error(`${timeoutMessage2} (${ms}ms)`))},ms);promise3.then((result)=>{clearTimeout(timer),resolve106(result)}).catch((error93)=>{clearTimeout(timer),reject(error93)})})}}init_pr_event_subscribers();init_pr_feedback_loop_runtime();init_pr_monitor_worker();init_queue();init_status_artifact();init_trigger();init_worker();import{createHash as createHash96}from"node:crypto";init_zod();init_task_envelope();init_workspace_snapshot();init_plan_schema();init_schema();init_plan_task_id_context();init_task_id_resolver();init_task_result_classifier();init_utils2();init_ledger();init_manager();init_utils3();init_atomic_write();init_canonical_root();init_lock();init_task_file();import{createHash as createHash95}from"node:crypto";import*as fs151 from"node:fs";import*as path273 from"node:path";var PHASE_PARTICIPATION_FILE="evidence/phase-participation.json",PHASE_PARTICIPATION_QUARANTINE_DIR="evidence/phase-participation-quarantine",MAX_PHASE_PARTICIPATION_BYTES=262144,MAX_PHASE_PARTICIPATION_PENDING=128,MAX_PHASE_PARTICIPATION_RECEIPTS=128,MAX_PHASE_PARTICIPATION_QUARANTINE_FILES=16,MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES=1048576,MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES=64,MAX_PENDING_IN_MEMORY=128,MAX_ID_CHARS=256,WorkspaceSchema2=exports_external.object({directory:exports_external.string().max(4096),gitHead:exports_external.string().max(256).nullable(),prHeadSha:exports_external.string().max(256).nullable()}).strict(),BindingSchema=exports_external.object({role:exports_external.string().min(1).max(120),prefixedRole:exports_external.string().min(1).max(120),planId:exports_external.string().min(1).max(512),planIdentityHash:exports_external.string().length(64),planStructureHash:exports_external.string().length(64),phase:exports_external.number().int().nonnegative(),taskId:exports_external.string().min(1).max(120).nullable(),parentSessionId:exports_external.string().min(1).max(MAX_ID_CHARS),callId:exports_external.string().min(1).max(MAX_ID_CHARS),policyDigest:exports_external.string().length(64),workspace:WorkspaceSchema2,capturedAt:exports_external.number().int().nonnegative()}).strict(),PendingSchema=BindingSchema.extend({childSessionId:exports_external.string().min(1).max(MAX_ID_CHARS)}).strict(),ReceiptSchema=PendingSchema.extend({receiptId:exports_external.string().length(64),resultDigest:exports_external.string().length(64),completedAt:exports_external.number().int().nonnegative(),childIdentityAvailable:exports_external.boolean()}).strict(),StoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),pending:exports_external.array(PendingSchema).max(MAX_PHASE_PARTICIPATION_PENDING),receipts:exports_external.array(ReceiptSchema).max(MAX_PHASE_PARTICIPATION_RECEIPTS)}).strict(),foregroundReservations=new Map;function emptyStore(){return{schemaVersion:1,pending:[],receipts:[]}}function correlationKey2(parentSessionId,callId){return`${parentSessionId}\x00${callId}`}function sha25610(value){return createHash95("sha256").update(value).digest("hex")}function policyDigest(policy){return sha25610(stableCanonicalStringify(policy??{}))}async function captureParticipationWorkspace(directory){let workspace=await captureWorkspaceSnapshotAsync(directory,{resolveCurrentPrHeadSha:!0});return{directory:workspace.directory,gitHead:workspace.gitHead,prHeadSha:workspace.prHeadSha}}function boundedPut(binding){let key2=correlationKey2(binding.parentSessionId,binding.callId);foregroundReservations.delete(key2),foregroundReservations.set(key2,binding);while(foregroundReservations.size>MAX_PENDING_IN_MEMORY){let oldest=foregroundReservations.keys().next().value;if(!oldest)break;foregroundReservations.delete(oldest)}}function takeBinding(parentSessionId,callId){let key2=correlationKey2(parentSessionId,callId),binding=foregroundReservations.get(key2)??null;return foregroundReservations.delete(key2),binding}async function persistWithBindingRecovery(directory,binding,operation){try{await withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",operation)}catch(error93){throw boundedPut(binding),error93}}async function buildBinding(input){return{role:stripKnownSwarmPrefix(input.role),prefixedRole:input.role,planId:derivePlanId(input.plan),planIdentityHash:derivePlanIdentityHash(input.plan),planStructureHash:receiptStructureHash(input.plan),phase:input.phase,taskId:input.taskId,parentSessionId:input.parentSessionId,callId:input.callId,policyDigest:policyDigest(input.policy),workspace:await captureParticipationWorkspace(input.directory),capturedAt:Date.now()}}function extractPlanTaskId2(args2,plan){let context=collectPlanTaskIdContextFromPhases(plan.phases),result=resolveTaskId(args2,{policy:"plan",...toTaskIdPlanContextOptions(context)});if(result.status!=="resolved")return null;if(context.status==="over_limit"&&!plan.phases.some((phase)=>phase?.tasks?.some((task2)=>task2?.id===result.taskId)))return null;return result.taskId}function storePath6(directory){return validateSwarmPath(directory,PHASE_PARTICIPATION_FILE)}function readRawStore(directory){let filePath;try{filePath=storePath6(directory)}catch(error93){return{status:"unreadable",error:error93}}let descriptor,bytes;try{let pathStat=fs151.lstatSync(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile())return{status:"unreadable",error:Error("Participation projection is not a regular file")};if(pathStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:pathStat.size};descriptor=fs151.openSync(filePath,fs151.constants.O_RDONLY|(fs151.constants.O_NOFOLLOW??0));let openedStat=fs151.fstatSync(descriptor);if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino)return{status:"unreadable",error:Error("Participation projection changed while it was being opened")};if(openedStat.size>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:openedStat.size};let bounded=Buffer.allocUnsafe(MAX_PHASE_PARTICIPATION_BYTES+1),offset=0;while(offset<bounded.byteLength){let read=fs151.readSync(descriptor,bounded,offset,bounded.byteLength-offset,null);if(read===0)break;offset+=read}if(offset>MAX_PHASE_PARTICIPATION_BYTES)return{status:"oversized",bytes:offset};bytes=bounded.subarray(0,offset)}catch(error93){if(error93.code==="ENOENT")return{status:"missing"};return{status:"unreadable",error:error93}}finally{if(descriptor!==void 0)try{fs151.closeSync(descriptor)}catch{}}try{return{status:"valid",store:StoreSchema.parse(JSON.parse(bytes.toString("utf8")))}}catch{return{status:"corrupt",bytes}}}async function atomicWriteBytes(filePath,bytes){await atomicWriteSwarmFile(filePath,bytes)}async function readBoundedRegularFile(filePath,maxBytes){let pathStat=await fs151.promises.lstat(filePath);if(pathStat.isSymbolicLink()||!pathStat.isFile()||pathStat.size>maxBytes)throw Error("bounded evidence artifact is not a permitted regular file");let handle=await fs151.promises.open(filePath,fs151.constants.O_RDONLY|(fs151.constants.O_NOFOLLOW??0));try{let openedStat=await handle.stat();if(!openedStat.isFile()||openedStat.dev!==pathStat.dev||openedStat.ino!==pathStat.ino||openedStat.size>maxBytes)throw Error("bounded evidence artifact changed while being opened");let bounded=Buffer.allocUnsafe(maxBytes+1),offset=0;while(offset<bounded.byteLength){let{bytesRead}=await handle.read(bounded,offset,bounded.byteLength-offset,null);if(bytesRead===0)break;offset+=bytesRead}if(offset>maxBytes)throw Error("bounded evidence artifact exceeds its byte limit");return bounded.subarray(0,offset)}finally{try{await handle.close()}catch{}}}function quarantineFullError(){return Error("PHASE_PARTICIPATION_QUARANTINE_FULL: preserved corrupt evidence reached its bounded retention limit; an operator must archive the quarantine before docs can be re-dispatched.")}async function quarantineCorruptBytes(directory,bytes){let digest4=sha25610(bytes),quarantineDir=validateSwarmPath(directory,PHASE_PARTICIPATION_QUARANTINE_DIR);await fs151.promises.mkdir(quarantineDir,{recursive:!0});let quarantineStat=await fs151.promises.lstat(quarantineDir);if(quarantineStat.isSymbolicLink()||!quarantineStat.isDirectory())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: quarantine is not a regular directory.");let target=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${digest4}.bin`);try{if(!(await readBoundedRegularFile(target,MAX_PHASE_PARTICIPATION_BYTES)).equals(bytes))throw Error("hash-addressed quarantine content mismatch");return}catch(error93){if(error93.code!=="ENOENT")throw error93}let count=0,totalBytes=0,scanned=0,handle=await fs151.promises.opendir(quarantineDir,{bufferSize:16});try{for await(let entry of handle){if(scanned+=1,scanned>MAX_PHASE_PARTICIPATION_QUARANTINE_DIRECTORY_ENTRIES)throw quarantineFullError();if(!entry.isFile()||!/^[a-f0-9]{64}\.bin$/.test(entry.name))continue;count+=1;let candidate2=validateSwarmPath(directory,`${PHASE_PARTICIPATION_QUARANTINE_DIR}/${entry.name}`),candidateStat=await fs151.promises.lstat(candidate2);if(candidateStat.isSymbolicLink()||!candidateStat.isFile())throw Error("PHASE_PARTICIPATION_QUARANTINE_UNREADABLE: invalid quarantine artifact.");if(totalBytes+=candidateStat.size,count>=MAX_PHASE_PARTICIPATION_QUARANTINE_FILES||totalBytes+bytes.byteLength>MAX_PHASE_PARTICIPATION_QUARANTINE_BYTES)throw quarantineFullError()}}finally{try{await handle.close()}catch{}}await atomicWriteBytes(target,bytes)}async function loadWritableStoreUnderLock(directory){let read=readRawStore(directory);if(read.status==="missing")return emptyStore();if(read.status==="valid")return read.store;if(read.status==="corrupt")return await quarantineCorruptBytes(directory,read.bytes),emptyStore();if(read.status==="oversized")throw Error(`PHASE_PARTICIPATION_OVERSIZED: ${read.bytes} bytes exceeds ${MAX_PHASE_PARTICIPATION_BYTES}; operator action is required before docs can be re-dispatched.`);throw Error("PHASE_PARTICIPATION_UNREADABLE: operator action is required before docs can be re-dispatched.")}async function writeStore3(directory,store){let validatedStore=StoreSchema.parse(store);validatedStore.pending.sort((left,right)=>left.capturedAt-right.capturedAt),validatedStore.receipts.sort((left,right)=>left.completedAt-right.completedAt);let serialized3=JSON.stringify(validatedStore,null,2);while(Buffer.byteLength(serialized3,"utf8")>MAX_PHASE_PARTICIPATION_BYTES){let pendingTime=validatedStore.pending[0]?.capturedAt??1/0,receiptTime=validatedStore.receipts[0]?.completedAt??1/0;if(pendingTime===1/0&&receiptTime===1/0)throw Error("PHASE_PARTICIPATION_WRITE_OVERSIZED: even an empty participation store exceeds its byte limit.");if(pendingTime<=receiptTime)validatedStore.pending.shift();else validatedStore.receipts.shift();validatedStore=StoreSchema.parse(validatedStore),serialized3=JSON.stringify(validatedStore,null,2)}await fs151.promises.mkdir(path273.dirname(storePath6(directory)),{recursive:!0}),await atomicWriteFile(storePath6(directory),serialized3)}function receiptStructureHash(plan){return computePlanStructureHash({...plan,current_phase:void 0})}function samePlanIdentity(binding,plan){return binding.planId===derivePlanId(plan)&&binding.planIdentityHash===derivePlanIdentityHash(plan)&&binding.planStructureHash===receiptStructureHash(plan)}function bindingMatchesPlan(binding,plan,phase){return samePlanIdentity(binding,plan)&&binding.phase===phase}function workspaceIdentityIsFresh(expected,current){return sameProjectRoot(expected.directory,current.directory)&&expected.gitHead===current.gitHead&&expected.prHeadSha===current.prHeadSha}function resultText(output){if(!output||typeof output!=="object")return{text:"",childSessionId:null};let record3=output,rawOutput=typeof record3.output==="string"?record3.output:"",envelope=parseTaskEnvelope(rawOutput);if(envelope?.state==="completed")return{text:envelope.resultText??"",childSessionId:envelope.sessionId};return{text:rawOutput,childSessionId:null}}function envelopeFromOutput(output){if(typeof output==="string")return parseTaskEnvelope(output);if(!output||typeof output!=="object")return null;let rawOutput=output.output;return typeof rawOutput==="string"?parseTaskEnvelope(rawOutput):null}function validateMetadata(output,parentSessionId,childSessionId){if(!output||typeof output!=="object")return{valid:!0,childSessionId};let metadata=output.metadata;if(!metadata||typeof metadata!=="object")return{valid:!0,childSessionId};let meta3=metadata;if(typeof meta3.parentSessionId==="string"&&meta3.parentSessionId!==parentSessionId)return{valid:!1,childSessionId:null};let metadataChild=typeof meta3.sessionId==="string"&&meta3.sessionId.length>0?meta3.sessionId:null;if(childSessionId&&metadataChild&&childSessionId!==metadataChild)return{valid:!1,childSessionId:null};return{valid:!0,childSessionId:childSessionId??metadataChild}}function computeReceiptId(input){return sha25610(stableCanonicalStringify({parentSessionId:input.parentSessionId,callId:input.callId,childSessionId:input.childSessionId,planIdentityHash:input.planIdentityHash,planStructureHash:input.planStructureHash,phase:input.phase,role:input.role}))}function addReceipt(store,pending,text,childIdentityAvailable){let receiptId=computeReceiptId(pending),receipt={...pending,receiptId,resultDigest:sha25610(text),completedAt:Date.now(),childIdentityAvailable};store.receipts=store.receipts.filter((existing)=>existing.receiptId!==receiptId&&!(existing.planIdentityHash===receipt.planIdentityHash&&existing.planStructureHash===receipt.planStructureHash&&existing.phase===receipt.phase&&existing.role===receipt.role)),store.receipts.push(receipt),store.receipts=store.receipts.slice(-MAX_PHASE_PARTICIPATION_RECEIPTS)}async function reserveApprovedPhaseParticipation(input){if(input.tool.toLowerCase()!=="task")return;let rawRole=input.args.subagent_type;if(typeof rawRole!=="string"||stripKnownSwarmPrefix(rawRole)!=="docs")return;let plan=await loadPlan(input.directory);if(!plan)return;let binding=await buildBinding({plan,phase:getCurrentPhase(plan),role:rawRole,parentSessionId:input.parentSessionId,callId:input.callId,taskId:extractPlanTaskId2(input.args,plan),policy:input.policy,directory:input.directory});await withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory);await writeStore3(input.directory,store)}),boundedPut(binding)}async function observePhaseParticipationToolResult(input){if(input.tool.toLowerCase()!=="task")return;let binding=takeBinding(input.parentSessionId,input.callId);if(!binding)return;let envelope=envelopeFromOutput(input.output);if(envelope?.state==="running"){let{subagentSessionId}=extractDispatchIds(input.output);if(!subagentSessionId||subagentSessionId!==envelope.sessionId)return;let pending2={...binding,childSessionId:subagentSessionId};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);store.pending=store.pending.filter((existing)=>existing.childSessionId!==pending2.childSessionId&&!(existing.parentSessionId===pending2.parentSessionId&&existing.callId===pending2.callId)),store.pending.push(pending2),store.pending=store.pending.slice(-MAX_PHASE_PARTICIPATION_PENDING),await writeStore3(input.directory,store)});return}if(envelope&&envelope.state!=="completed")return;if(classifyTaskResult(input.output)!=="success")return;let extracted=resultText(input.output),text=extracted.text.trim();if(!text)return;let metadata=validateMetadata(input.output,input.parentSessionId,extracted.childSessionId);if(!metadata.valid)return;let childSessionId=metadata.childSessionId,currentPlan=await loadPlan(input.directory);if(!currentPlan||!bindingMatchesPlan(binding,currentPlan,binding.phase))return;if(!workspaceIdentityIsFresh(binding.workspace,await captureParticipationWorkspace(input.directory)))return;let pending={...binding,childSessionId:childSessionId??`unavailable:${sha25610(correlationKey2(input.parentSessionId,input.callId))}`};await persistWithBindingRecovery(input.directory,binding,async()=>{let store=await loadWritableStoreUnderLock(input.directory);addReceipt(store,pending,text,childSessionId!==null),await writeStore3(input.directory,store)})}async function completeBackgroundPhaseParticipation(input){if(stripKnownSwarmPrefix(input.record.normalizedAgent)!=="docs")return!1;let text=input.resultText.trim();if(!text)return!1;return withEvidenceLock(input.directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(input.directory),currentPlan=await loadPlan(input.directory),existingReceipt=store.receipts.find((receipt)=>receipt.childSessionId===input.record.subagentSessionId&&receipt.parentSessionId===input.record.parentSessionId&&receipt.callId===input.record.callID&&receipt.role===input.record.normalizedAgent&&receipt.prefixedRole===input.record.swarmPrefixedAgent&&receipt.taskId===input.record.planTaskId);if(existingReceipt&&currentPlan&&bindingMatchesPlan(existingReceipt,currentPlan,existingReceipt.phase))return!0;let pending=store.pending.find((candidate2)=>candidate2.childSessionId===input.record.subagentSessionId&&candidate2.parentSessionId===input.record.parentSessionId&&candidate2.callId===input.record.callID&&candidate2.role===input.record.normalizedAgent&&candidate2.prefixedRole===input.record.swarmPrefixedAgent&&candidate2.taskId===input.record.planTaskId);if(!pending)return!1;let plan=currentPlan;if(!plan||!bindingMatchesPlan(pending,plan,pending.phase))return!1;if(!workspaceIdentityIsFresh(pending.workspace,await captureParticipationWorkspace(input.directory)))return!1;if(pending.taskId!==null&&input.record.ingestion?.state!=="consumed")return!1;return addReceipt(store,pending,text,!0),store.pending=store.pending.filter((candidate2)=>candidate2.childSessionId!==pending.childSessionId),await writeStore3(input.directory,store),!0})}async function readPhaseParticipation(directory,plan,phase,role){let read=readRawStore(directory);if(read.status!=="valid")return{status:read.status,found:!1};let canonicalRole2=stripKnownSwarmPrefix(role),currentWorkspace=await captureParticipationWorkspace(directory),cursorPhase=getCurrentPhase(plan);return{status:"valid",found:read.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&workspaceIdentityIsFresh(receipt.workspace,currentWorkspace)&&(receipt.phase===phase||receipt.phase===cursorPhase&&cursorPhase<phase))}}async function rebindCursorTaggedReceipts(directory,plan,phase,role){let canonicalRole2=stripKnownSwarmPrefix(role),cursorPhase=getCurrentPhase(plan),peek=readRawStore(directory);if(!(peek.status==="valid"&&peek.store.receipts.some((receipt)=>receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)))return{rebound:0};return withEvidenceLock(directory,PHASE_PARTICIPATION_FILE,"docs","phase-participation",async()=>{let store=await loadWritableStoreUnderLock(directory),rebound=0;for(let receipt of store.receipts)if(receipt.role===canonicalRole2&&samePlanIdentity(receipt,plan)&&receipt.phase===cursorPhase&&cursorPhase<phase)receipt.phase=phase,receipt.receiptId=computeReceiptId(receipt),rebound+=1;if(rebound>0){let newestByKey=new Map;for(let receipt of store.receipts.slice().sort((left,right)=>left.completedAt-right.completedAt))newestByKey.set(`${receipt.planIdentityHash}\x00${receipt.planStructureHash}\x00${receipt.phase}\x00${receipt.role}`,receipt);store.receipts=[...newestByKey.values()],await writeStore3(directory,store)}return{rebound}})}init_gate_evidence();init_worktree_isolation();init_helpers();init_state2();init_canonical_root();init_logger();init_coder_settlement();init_merge2();init_pending_delegations();init_loader();init_task_gate_requirements();init_gate_evidence();init_gate_evidence_classification();init_review_receipt_collector();init_reviewer_scope_file_fingerprint();init_routing_enforcement();init_scope_binding();init_state2();init_logger();init_workspace_snapshot();var GATE_EVIDENCE_ROLES=new Set(["reviewer","test_engineer","docs","designer","critic","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","explorer","sme"]);function structuredStageBVerdict(role,text,taskId){let escapedTaskId=taskId.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),match=(role==="reviewer"?new RegExp(`^\\[REVIEWED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(APPROVED|REJECTED|CONCERNS)\\s*\\|`,"im"):new RegExp(`^\\[TESTED\\]\\s*\\|\\s*(?:task-)?${escapedTaskId}\\s*\\|\\s*(PASS|FAIL|SKIPPED)\\s*\\|`,"im")).exec(text);if(!match)return null;if(match[1]==="APPROVED"||match[1]==="PASS")return"pass";if(match[1]==="SKIPPED")return"skip";return"fail"}function normalizeAttributionPath(file3){let normalized=file3.trim().replaceAll("\\","/").replace(/^\.\/+/,""),hasControlCharacter5=[...normalized].some((character)=>{let code=character.charCodeAt(0);return code<=31||code===127});if(!normalized||normalized.startsWith("/")||/^[A-Za-z]:\//.test(normalized)||normalized===".."||normalized.startsWith("../")||normalized.split("/").includes("..")||hasControlCharacter5)return null;return normalized}function normalizedPathSet(files){if(!files)return null;let normalized=new Set;for(let file3 of files){let candidate2=normalizeAttributionPath(file3);if(!candidate2)return null;normalized.add(candidate2)}return normalized}function pathSetsEqual(left,right){return left.size===right.size&&[...left].every((file3)=>right.has(file3))}function hasDistinctBackgroundOwner(input){if(!Number.isFinite(input.candidateCreatedAt)||!Number.isFinite(input.candidateCompletedAt)||input.candidateCreatedAt>input.candidateCompletedAt)return!1;let liveOwners=[...(swarmState.agentSessions.get(input.parentSessionID)?.reviewerScopeGenerations??new Map).values()].filter((generation)=>{if(generation.background!==!0||generation.taskId===input.taskId&&generation.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(generation.declaredFiles),routed=normalizedPathSet(generation.modifiedFiles),fingerprints=generation.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file),ownerCompletedAt=generation.readyAt??input.candidateCompletedAt;return Number.isFinite(generation.createdAt)&&Number.isFinite(ownerCompletedAt)&&generation.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=ownerCompletedAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)}),historicalOwners=getReviewerScopeOwnershipHistory({parentSessionID:input.parentSessionID}).filter((owner)=>{if(owner.taskId===input.taskId&&owner.coderCallID===input.coderCallID)return!1;let declared=normalizedPathSet(owner.declaredFiles),routed=normalizedPathSet(owner.modifiedFiles),fingerprints=owner.modifiedFileFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===input.file);return owner.parentSessionID===input.parentSessionID&&owner.background===!0&&Number.isFinite(owner.createdAt)&&Number.isFinite(owner.readyAt)&&owner.createdAt<=input.candidateCompletedAt&&input.candidateCreatedAt<=owner.readyAt&&declared?.has(input.file)===!0&&routed?.has(input.file)===!0&&fingerprints.length===1&&reviewerScopeFileFingerprintsEqual(fingerprints[0],input.fingerprint)});return liveOwners.length+historicalOwners.length===1}function isBackgroundGateBearingRecord(record3){return record3.batchId===void 0&&record3.evidenceTaskId!==null&&GATE_EVIDENCE_ROLES.has(record3.normalizedAgent)}function validateStageBWorkspace(directory,record3){let actualWorkspace=captureWorkspaceSnapshot(directory,{scope:record3.workspace?.scope??null,prHeadSha:record3.workspace?.prHeadSha??null,resolveCurrentPrHeadSha:record3.workspace?.prHeadSha!==null}),check3=compareStageBWorkspace(record3,actualWorkspace,directory);return{...check3,ok:!check3.stale}}var BARE_TASK_ID=/^\d+(?:\.\d+)*$/,SCOPE_CASE_FOLD=process.platform==="win32";function scopeMatchKey(normalized){return SCOPE_CASE_FOLD?normalized.toLowerCase():normalized}function deriveScopeFiles(scope){if(!scope)return null;let files=new Set;for(let fragment of scope.split(",")){let normalized=normalizeAttributionPath(fragment);if(normalized===null||BARE_TASK_ID.test(normalized))continue;files.add(scopeMatchKey(normalized))}return files.size>0?files:null}function scopeDirtySlice(files,scopeFiles){let slice=new Set;for(let file3 of files){let normalized=normalizeAttributionPath(file3);if(normalized!==null&&scopeFiles.has(scopeMatchKey(normalized)))slice.add(normalized)}return slice}function compareStageBWorkspace(record3,actualWorkspace,directory){let expectedWorkspace=record3.normalizedAgent==="docs"&&record3.workspace?{...record3.workspace,dirtyHash:null}:record3.workspace;if(!expectedWorkspace)return{stale:!1};if(record3.normalizedAgent==="docs")return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let scopeFiles=deriveScopeFiles(expectedWorkspace.scope),expectedHead=expectedWorkspace.gitHead,currentHead=actualWorkspace.gitHead,expectedChanged=expectedWorkspace.changedFiles,currentChanged=actualWorkspace.changedFiles;if(scopeFiles===null||expectedHead==null||currentHead==null||expectedChanged==null||currentChanged==null||directory===void 0)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let identity=workspaceSnapshotMatches({...expectedWorkspace,gitHead:null,dirtyHash:null},{...actualWorkspace,gitHead:null,dirtyHash:null});if(!identity.ok)return{stale:!0,reason:identity.reason};let committed=committedFilesBetween(directory,expectedHead,currentHead);if(committed===null)return compareWorkspaceSnapshots(expectedWorkspace,actualWorkspace);let committedInScope=committed.filter((file3)=>scopeFiles.has(scopeMatchKey(normalizeAttributionPath(file3)??"")));if(committedInScope.length>0){let shown=committedInScope.slice(0,5).join(", "),extra=committedInScope.length>5?` (+${committedInScope.length-5} more)`:"";return{stale:!0,reason:`in-scope committed change: ${shown}${extra}`}}let dispatchDirty=scopeDirtySlice(expectedChanged,scopeFiles),currentDirty=scopeDirtySlice(currentChanged,scopeFiles),dirtied=[...currentDirty].filter((file3)=>!dispatchDirty.has(file3)),cleaned=[...dispatchDirty].filter((file3)=>!currentDirty.has(file3));if(dirtied.length>0||cleaned.length>0)return{stale:!0,reason:`in-scope dirty set changed: +[${dirtied.join(", ")}] -[${cleaned.join(", ")}]`};return{stale:!1}}async function ingestBackgroundStageBCompletion(args2){let taskId=args2.record.evidenceTaskId??args2.record.planTaskId;if(!taskId)return{ok:!0,consumed:!1};if(args2.record.normalizedAgent==="coder"){let taskChangeContext=args2.record.taskChangeContext,settledFiles=args2.record.coderSettlement?.state==="settled"?args2.record.coderSettlement.observedFiles:void 0,observedFiles=settledFiles!==void 0?settledFiles:taskChangeContext?changedFilesSinceSnapshot(taskChangeContext.baseline.directory,taskChangeContext.baseline):null;if(observedFiles===null)return{ok:!1,consumed:!1,stale:!0,reason:"background coder files could not be attributed to a clean immutable baseline"};try{let observedSet=normalizedPathSet(observedFiles),declaredSet=normalizedPathSet(taskChangeContext?.declaredFiles??null),completionTime=args2.record.completedAt??args2.record.updatedAt,attributedFiles=observedFiles??[];if(args2.reviewerReceiptOptions?.config?.enabled!==!0){if(observedSet&&declaredSet)attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3))}if(args2.reviewerReceiptOptions?.config?.enabled===!0){if(!observedSet||!declaredSet)return{ok:!1,consumed:!1,reason:"background coder changed-file attribution could not be reconstructed exactly"};attributedFiles=[...observedSet].filter((file3)=>declaredSet.has(file3));let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),generationScope=normalizedPathSet(generation?.declaredFiles??null),routedFiles=normalizedPathSet(generation?.modifiedFiles??null),routedFingerprints=generation?.modifiedFileFingerprints??null;if(generation?.status==="collecting"&&generation.background===!0&&observedSet.size===0&&routedFiles?.size===0&&declaredSet){if(markReviewerScopeGenerationNoChange({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}))return{ok:!0,consumed:!0}}let captureRoot=generation?.captureDirectory?.trim()||args2.directory,observedFingerprints=new Map;for(let file3 of observedSet){let captured=captureReviewerScopeFileFingerprint(captureRoot,file3);if(captured.kind==="capture_failed")return{ok:!1,consumed:!1,reason:`background coder post-write fingerprint could not be reconstructed exactly (${captured.code}${captured.retryable?" (retryable)":" (permanent)"} on ${captured.file})`};let fingerprint2=reviewerScopeCaptureToFingerprint(captured);if(!fingerprint2)return{ok:!1,consumed:!1,reason:"background coder post-write fingerprint returned an unusable result"};observedFingerprints.set(file3,fingerprint2)}let changedWithinDeclaredScope=new Set([...observedSet].filter((file3)=>declaredSet.has(file3)&&generationScope?.has(file3))),observedOutsideCurrentScope=[...observedSet].filter((file3)=>!generationScope?.has(file3));if(generation?.status!=="collecting"&&generation?.status!=="ready"||generation.background!==!0||!generationScope||!routedFiles||!routedFingerprints||routedFiles.size===0||!pathSetsEqual(declaredSet,generationScope)||!pathSetsEqual(routedFiles,changedWithinDeclaredScope)||reviewerScopeGenerationHasDeclaredOverlap({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,declaredFiles:generation.declaredFiles})||observedOutsideCurrentScope.some((file3)=>!hasDistinctBackgroundOwner({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,file:file3,fingerprint:observedFingerprints.get(file3),candidateCreatedAt:args2.record.createdAt,candidateCompletedAt:completionTime}))||[...routedFiles].some((file3)=>{let fingerprints=routedFingerprints.filter((entry)=>normalizeAttributionPath(entry.file)===file3),observedFingerprint=observedFingerprints.get(file3);return!observedSet.has(file3)||!declaredSet.has(file3)||!generationScope.has(file3)||fingerprints.length!==1||!observedFingerprint||!reviewerScopeFileFingerprintsEqual(fingerprints[0],observedFingerprint)}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be reconstructed exactly"};attributedFiles=[...routedFiles];for(let file3 of routedFiles){let fingerprint2=observedFingerprints.get(file3);if(fingerprint2)recordReviewerScopeGenerationFileFingerprint({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,fingerprint:fingerprint2})}}let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){let state2=getTaskState(parentSession,taskId);if(state2!=="idle"&&state2!=="coder_delegated"&&state2!=="rework_required")return{ok:!1,consumed:!1,reason:`background coder completion is late for task ${taskId}: current state is ${state2}`}}let accepted=attributedFiles.length>0,expectedGeneration=args2.record.taskChangeContext?.workflowGeneration??0,transitionId=`background-coder:${args2.record.correlationId}`,existingEvidence=await readTaskEvidence(args2.directory,taskId),existingWorkflow=getTaskWorkflowSnapshot(existingEvidence),updated=existingWorkflow.authoritative&&existingWorkflow.lastTransitionId===transitionId&&existingWorkflow.lastOutcome===(accepted?"accepted_mutation":"dispatch_no_mutation")&&existingWorkflow.generation===expectedGeneration+(accepted?1:0)?existingEvidence:await transitionTaskWorkflowEvidence(args2.directory,taskId,accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:isMarkdownOnlyTaskChange(taskChangeContext?.declaredFiles,attributedFiles)},expectedGeneration,transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId});if(accepted){let workflow=getTaskWorkflowSnapshot(updated),parentSession2=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession2){if(!recordModifiedFilesForTask(parentSession2,taskId,attributedFiles))warn(`[background] durable coder mutation for ${taskId} exceeded session file-attribution capacity`);parentSession2.taskWorkflowStates.set(taskId,"coder_delegated"),parentSession2.stageBCompletion?.delete(taskId),parentSession2.taskCouncilApproved?.delete(taskId),parentSession2.taskCouncilWorkflowGeneration?.delete(taskId),updateTaskWorkflowCache(parentSession2,taskId,workflow)}}if(args2.reviewerReceiptOptions?.config?.enabled===!0){let laneGeneration=getReviewerScopeGenerationForCoderCall({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID});if(laneGeneration!==null&&laneGeneration.workspaceIdentity!==canonicalWorkspaceIdentity(args2.directory))return markReviewerScopeGenerationMergebackPending({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID}),{ok:!0,consumed:!0}}if(args2.reviewerReceiptOptions?.config?.enabled===!0&&!markReviewerScopeGenerationReady({parentSessionID:args2.record.parentSessionId,taskId,coderCallID:args2.record.callID,primaryWorkspaceIdentity:canonicalWorkspaceIdentity(args2.directory)??void 0}))return{ok:!1,consumed:!1,reason:"background coder scope handoff could not be marked ready after evidence persisted"};return{ok:!0,consumed:!0}}catch(err){return{ok:!1,consumed:!1,reason:`background coder evidence ingestion failed: ${err instanceof Error?err.message:String(err)}`}}}if(!isBackgroundGateBearingRecord(args2.record))return{ok:!0,consumed:!1};let workspaceCheck=validateStageBWorkspace(args2.directory,args2.record);if(workspaceCheck.stale)return{ok:!1,consumed:!1,stale:!0,reason:workspaceCheck.reason??"workspace changed while gate was running"};try{if(args2.record.workflowGeneration===void 0)return{ok:!1,consumed:!1,reason:`stage-b ingestion failed: TASK_WORKFLOW_GENERATION_REQUIRED for ${taskId}`};let existingEvidence=await readTaskEvidence(args2.directory,taskId),stageBRole=args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer"?args2.record.normalizedAgent:null,verdict=stageBRole?structuredStageBVerdict(stageBRole,args2.result.text??"",taskId):null;if(stageBRole&&verdict==="skip")return{ok:!1,consumed:!0,skipped:!0,reason:`background ${stageBRole} skipped task ${taskId} — tests not run; re-dispatch the test gate (task stays Stage B eligible; reviewer proof preserved)`};if(stageBRole&&verdict!=="pass"){let rejected2=await transitionTaskWorkflowEvidence(args2.directory,taskId,{type:"stage_b_failed",gate:stageBRole,expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate-failed:${args2.record.correlationId}`}),parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession)parentSession.taskWorkflowStates.set(taskId,"rework_required"),parentSession.stageBCompletion?.delete(taskId),updateTaskWorkflowCache(parentSession,taskId,getTaskWorkflowSnapshot(rejected2));return{ok:!1,consumed:!0,reason:verdict==="fail"?`background ${stageBRole} rejected task ${taskId}`:`background ${stageBRole} returned no valid structured verdict for task ${taskId}`}}let preparedRoute,routeCompleteForPersistence;if(stageBRole){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(parentSession){preparedRoute=resolveBackgroundStageBRoute({directory:args2.directory,taskId,parentSessionId:args2.record.parentSessionId,role:stageBRole,callId:args2.record.callID,childSessionId:args2.record.subagentSessionId,generation:args2.record.workflowGeneration,session:parentSession});let routeEnabled=(()=>{try{return loadPluginConfig(args2.directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),routeDecision=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:routeEnabled,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:preparedRoute.binding?{role:preparedRoute.binding.role,identity:preparedRoute.binding.identity,callId:preparedRoute.binding.callId,childSessionId:preparedRoute.binding.childSessionId,generation:preparedRoute.binding.generation}:void 0});if(!routeDecision.canAdvance)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: ${routeDecision.reason??"unknown reason"}`),{ok:!1,consumed:!1,reason:`route receipt blocked before Stage-B evidence publication: ${routeDecision.reason??"unknown reason"}`};if(routeEnabled&&preparedRoute.route?.kind==="review_route_receipt")routeCompleteForPersistence=enforcePersistedReviewRouteReceipt({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId,receipts:preparedRoute.prospective,enforcementEnabled:!0,legacyUnrouted:preparedRoute.legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance}else{let route=readReviewRouteReceiptSync({projectRoot:args2.directory,sessionId:args2.record.parentSessionId,taskId});if(route?.kind!=="review_route_router_error"||route.sessionId!==args2.record.parentSessionId||route.taskId!==taskId)return{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session is unavailable and recovery receipt is not identity-bound"}}}let routeEvidenceRollback=null;if(preparedRoute?.binding){let parentSession=swarmState.agentSessions.get(args2.record.parentSessionId);if(!parentSession)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: parent session unavailable`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: parent session unavailable"};if(routeEvidenceRollback=reserveStageBRouteEvidence(parentSession,taskId,preparedRoute.binding),!routeEvidenceRollback)return warn(`[background-stage-b] route receipt blocked before evidence publication for ${taskId}: bounded route evidence capacity exceeded`),{ok:!1,consumed:!1,reason:"route receipt blocked before Stage-B evidence publication: bounded route evidence capacity exceeded"}}try{await recordGateEvidence(args2.directory,taskId,args2.record.normalizedAgent,args2.record.subagentSessionId,hasActiveTurboMode(args2.record.parentSessionId),{expectedGeneration:args2.record.workflowGeneration,transitionId:`background-gate:${args2.record.correlationId}`,ensureDefaultStageB:existingEvidence?.test_engineer_exempt!==!0,routeBinding:preparedRoute?.binding,routeComplete:routeCompleteForPersistence})}catch(err){throw routeEvidenceRollback?.(),err}if(args2.record.normalizedAgent==="reviewer")await collectReviewerReceiptFromTranscript(args2.directory,{targetAgent:args2.record.swarmPrefixedAgent,prompt:args2.record.prompt?.text??"",transcript:args2.result.text??"",sessionID:args2.record.parentSessionId,taskId,reviewerCallID:args2.record.callID,consumeHandoff:!0},args2.reviewerReceiptOptions);if(args2.record.normalizedAgent==="reviewer"||args2.record.normalizedAgent==="test_engineer")applyStageBStateCompletion(taskId,args2.record.normalizedAgent,args2.record.parentSessionId,existingEvidence?.test_engineer_exempt===!0,args2.directory,args2.record.callID,args2.record.subagentSessionId,args2.record.workflowGeneration,preparedRoute);return{ok:!0,consumed:!0}}catch(err){let message=err instanceof Error?err.message:String(err);return warn(`[background-stage-b] ingestion failed: ${message}`),{ok:!1,consumed:!1,reason:`stage-b ingestion failed: ${message}`}}}function candidateSessions(parentSessionId){let parent=swarmState.agentSessions.get(parentSessionId);return parent?[parent]:[]}function routeDispatchKey(entry){if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")}function resolveBackgroundStageBRoute(input){let route=readReviewRouteReceiptSync({projectRoot:input.directory,sessionId:input.parentSessionId,taskId:input.taskId}),evidence2=getStageBRouteEvidence(input.session,input.taskId);if(evidence2.length===0)try{evidence2=routeEvidenceFromTaskGateRequirements(readTaskGateRequirementsReceiptsSync(input.directory,input.taskId))}catch{}let legacyUnrouted=route===null&&!isStageBRouteRequired(input.session,input.taskId)&&(()=>{try{let receipts=readTaskGateRequirementsReceiptsSync(input.directory,input.taskId);return receipts.length>0&&receipts.every((receipt)=>!receipt.routeBinding)}catch{return!1}})(),binding,prospective=evidence2;if(route?.kind==="review_route_receipt"){let identities=input.role==="reviewer"?route.identities.reviewers:route.identities.testEngineers,slots=input.role==="reviewer"?route.slots?.reviewers??identities:route.slots?.testEngineers??identities,dispatchKey2=[input.role,input.parentSessionId,input.taskId,input.callId,input.childSessionId,String(input.generation)].join("\x00"),retry=evidence2.find((entry)=>entry.role===input.role&&routeDispatchKey(entry)===dispatchKey2),usedSlots=new Set(evidence2.filter((entry)=>entry.role===input.role&&entry!==retry&&entry.slotId).map((entry)=>entry.slotId)),slotIndex=retry?slots.indexOf(retry.slotId??""):slots.findIndex((slot)=>!usedSlots.has(slot));if(slotIndex>=0&&slotIndex<identities.length){let slotId=slots[slotIndex],identity=identities[slotIndex];binding={role:input.role,identity,sessionId:input.parentSessionId,taskId:input.taskId,slotId,callId:input.callId,childSessionId:input.childSessionId,generation:input.generation},prospective=retry?evidence2.map((entry)=>entry===retry?binding:entry):[...evidence2,binding]}}return{route,binding,prospective,legacyUnrouted}}function applyStageBStateCompletion(taskId,agent,parentSessionId,testEngineerExempt,directory,callId,childSessionId,generation,preparedRoute){for(let session of candidateSessions(parentSessionId)){let resolvedRoute=preparedRoute??resolveBackgroundStageBRoute({directory,taskId,parentSessionId,role:agent,callId,childSessionId,generation:generation??-1,session}),{binding,prospective:routeEvidence,legacyUnrouted}=resolvedRoute,routeEnabled=(()=>{try{return loadPluginConfig(directory).review_routing?.enforce_receipts??!0}catch{return!0}})(),completionDecision=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:routeEvidence,enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!1,expectedDispatch:binding?{role:binding.role,identity:binding.identity,callId:binding.callId,childSessionId:binding.childSessionId,generation:binding.generation}:void 0});if(!completionDecision.canAdvance){warn(`[background-stage-b] route receipt blocked ${taskId}: ${completionDecision.reason??"unknown reason"}`);continue}if(binding&&!recordStageBRouteEvidence(session,taskId,binding)){warn(`[background-stage-b] route receipt blocked before Stage-B evidence publication for ${taskId}: bounded route evidence capacity exceeded`);continue}recordStageBCompletion(session,taskId,agent);let state2=getTaskState(session,taskId);if(state2==="tests_run"||state2==="complete")continue;let routeComplete=enforcePersistedReviewRouteReceipt({projectRoot:directory,sessionId:parentSessionId,taskId,receipts:getStageBRouteEvidence(session,taskId),enforcementEnabled:routeEnabled,legacyUnrouted,requireEvidenceBindings:!0,requireCompleteEvidence:!0}).canAdvance;if(routeComplete&&(hasBothStageBCompletions(session,taskId)||testEngineerExempt&&agent==="reviewer")){try{if(state2==="coder_delegated"||state2==="pre_check_passed")advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId});if(getTaskState(session,taskId)==="reviewer_run")advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} after ${agent}: ${err instanceof Error?err.message:String(err)}`)}continue}if(agent==="reviewer"&&(state2==="coder_delegated"||state2==="pre_check_passed"))try{advanceTaskState(session,taskId,"reviewer_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to reviewer_run: ${err instanceof Error?err.message:String(err)}`)}else if(routeComplete&&agent==="test_engineer"&&state2==="reviewer_run")try{advanceTaskState(session,taskId,"tests_run",{telemetrySessionId:parentSessionId})}catch(err){warn(`[background-stage-b] could not advance ${taskId} to tests_run: ${err instanceof Error?err.message:String(err)}`)}}}init_task_envelope();init_workspace_snapshot();var RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),observerInternals={transferCoderSettlementToBackground,markLegacyCoderSettlementTransferPending,sleep:(milliseconds)=>new Promise((resolve106)=>setTimeout(resolve106,milliseconds))};function createBackgroundCompletionObserver(opts){let{config:config3,directory}=opts,replayInProgress=!1,notifyLegacyCoderSettlementAdvisoryReplaced=(record3,replacement)=>{let session=swarmState.agentSessions.get(record3.parentSessionId);if(!session)return;if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,replacement.advisory.eventId),replacement.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage]);pushAdvisory(session,replacement.advisory.message)},event=async(input)=>{if(!config3.enabled)return;try{let pending,result,terminal,record3,text,isDuplicate=!1;if(input.trustedTerminal)pending=input.trustedTerminal.record,result=input.trustedTerminal.result,terminal=input.trustedTerminal.terminal,text=result.error??result.text??"",record3=pending,isDuplicate=!0;else{let evt=input?.event;if(!evt||evt.type!=="message.part.updated")return;let part=evt.properties?.part;if(!part||part.type!=="text"||part.synthetic!==!0||typeof part.text!=="string")return;let envelope=parseTaskEnvelope(part.text);if(!envelope||envelope.state!=="completed"&&envelope.state!=="error"&&envelope.state!=="cancelled")return;let parentSessionId=typeof part.sessionID==="string"?part.sessionID:"",lookup=await findDelegationForCompletion(directory,envelope.sessionId);if(lookup?.source==="uncertain"){warn(`[background] deferring terminal ingestion: delegation store unreadable for ${envelope.sessionId} (${lookup.uncertain})`);return}if(!lookup){log(`[background] trusted completion for ${envelope.sessionId} has no durable primary or fallback owner; ignored`);return}if(!parentSessionId||lookup.record.parentSessionId!==parentSessionId||lookup.record.subagentSessionId!==envelope.sessionId){warn(`[background] trusted completion identity mismatch for ${envelope.sessionId}; ignored`);return}if(pending=lookup.record,lookup.source==="fallback"){let promoted=await promoteDelegationFallback(directory,envelope.sessionId);if(!promoted){warn(`[background] fallback promotion failed for ${envelope.sessionId}; terminal work remains preserved`);return}pending=promoted.record}text=envelope.state==="error"||envelope.state==="cancelled"?envelope.errorText??"":envelope.resultText??"",result={...envelope.state==="error"?{error:text}:{text},chars:envelope.resultChars??text.length,truncated:envelope.resultTruncated??!1,digest:digest4(text)},terminal={eventId:buildBackgroundCompletionEventId({correlationId:pending.correlationId,jobId:pending.jobId,status:envelope.state,resultDigest:result.digest}),status:envelope.state,recordedAt:pending.terminalResult?.recordedAt??Date.now(),result};let terminalClaim=await claimTerminalResult(directory,pending.correlationId,terminal);if(!terminalClaim){warn(`[background] terminal claim failed for ${pending.correlationId}; ignored`);return}isDuplicate=terminalClaim.disposition==="duplicate",record3=terminalClaim.record}if(opts.onTerminalClaimed?.(record3),!input.trustedTerminal?.skipMaintenance)try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"trusted-terminal",onLegacyCoderSettlementReconciled:reconcilePending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}let legacyTransferPending=!1,legacyTransferRequiresManualRecovery=!1;if(terminal.status!=="completed"){if(isDuplicate&&record3.normalizedAgent!=="coder")return;if(record3.normalizedAgent==="coder"){let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0;if(record3.planTaskId){let expectedGeneration=record3.taskChangeContext?.workflowGeneration;if(expectedGeneration===void 0)warn(`[background] failed coder ${record3.correlationId} has no launch generation for task ${record3.planTaskId}`);else try{await transitionTaskWorkflowEvidence(directory,record3.planTaskId,{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration,transitionId:`background-coder-terminal:${terminal.eventId}`})}catch(error93){warn(`[background] failed coder retry accounting was fenced for ${record3.planTaskId}: ${error93 instanceof Error?error93.message:String(error93)}`)}}try{await releaseCoderReservation(directory,record3,"recovered")}catch(error93){warn(`[background] failed coder reservation cleanup will be retried by admission reconciliation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.worktree){let descriptor=record3.worktree;if(!standardWorktreeByCallID.has(record3.callID))standardWorktreeByCallID.set(record3.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}});try{await abortStandardWorktreeDispatch(record3.callID,"cancelled",directory)}catch(error93){warn(`[background] failed coder worktree cleanup preserved the lane for manual recovery: ${error93 instanceof Error?error93.message:String(error93)}`)}}}if(discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,legacyTransferPending?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement transfer is pending; durable reconciliation will retry`:legacyTransferRequiresManualRecovery?`${terminal.status==="cancelled"?"cancelled":"failed"}; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)`:terminal.status==="cancelled"?"cancelled":"failed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId);return}if(record3.normalizedAgent==="coder"){let settled=await settleCoder(directory,record3,terminal.eventId);if(record3=settled.record,!settled.ok){await publishAdvisory(directory,record3,terminal.eventId,settled.outcome);return}let legacyTransfer=await transferLegacyCoderSettlement(directory,record3);if(legacyTransfer.disposition==="retry_pending")legacyTransferPending=!0;else if(legacyTransfer.disposition==="manual_recovery")legacyTransferRequiresManualRecovery=!0}else if(!isDuplicate&&isBackgroundGateBearingRecord(record3)){if(validateStageBWorkspace(directory,record3).stale){await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),discardScopeForRecord(record3),await publishAdvisory(directory,record3,terminal.eventId,"stale");return}}if(record3.normalizedAgent==="coder"||isBackgroundGateBearingRecord(record3)){let ingestion=await claimDelegationIngestion(directory,record3.correlationId,{claimantId:terminal.eventId});if(ingestion?.disposition==="claimed"||ingestion?.disposition==="retry"){let applied2=await ingestBackgroundStageBCompletion({directory,record:ingestion.record,result:ingestion.record.result??result,reviewerReceiptOptions:opts.reviewerReceiptOptions}),claimToken=ingestion.record.ingestion?.claimToken;if(!claimToken){await publishAdvisory(directory,record3,terminal.eventId,"ingestion claim token missing");return}let ingestionCommit=await(opts.recordIngestionResult??recordDelegationIngestionResult)(directory,record3.correlationId,claimToken,applied2.ok);if(!ingestionCommit){warn(`[background] ingestion claim for ${record3.correlationId} expired or was fenced before commit; retry remains pending`);return}if(applied2.ok&&(ingestionCommit.status!=="consumed"||ingestionCommit.ingestion?.state!=="consumed"||ingestionCommit.ingestion.claimToken!==claimToken)){warn(`[background] ingestion commit for ${record3.correlationId} did not confirm the exact consumed claim; retry remains pending`);return}if(record3=ingestionCommit,record3=(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,!applied2.ok){await publishAdvisory(directory,record3,terminal.eventId,applied2.skipped?"skipped (tests not run) — re-dispatch the test gate; reviewer proof preserved; task remains Stage B eligible":legacyTransferPending?"ingestion failed; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"ingestion failed; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":applied2.stale?"stale":"ingestion failed");try{await maintainBackgroundDelegations(directory,{lockTimeoutMs:1000,reason:"ingestion-rejection",skipLegacyCoderSettlementReconciliation:legacyTransferPending,onLegacyCoderSettlementAdvisoryReplaced:notifyLegacyCoderSettlementAdvisoryReplaced})}catch{}return}}else if(ingestion?.disposition==="busy")return;else if(ingestion?.disposition!=="consumed"){await publishAdvisory(directory,record3,terminal.eventId,"ingestion pending");return}}if(record3.normalizedAgent==="docs")try{if(!await completeBackgroundPhaseParticipation({directory,record:record3,resultText:text}))warn(`[background] docs completion ${record3.correlationId} did not satisfy its durable phase-participation binding`)}catch(error93){warn(`[background] docs completion ${record3.correlationId} could not persist phase participation: ${error93 instanceof Error?error93.message:String(error93)}`)}if(record3.normalizedAgent==="reviewer")discardScopeForRecord(record3);if(record3.normalizedAgent==="coder"){if(await releaseCoderReservation(directory,record3,"consumed"),!legacyTransferPending)await clearLegacyCoderSettlementTransferPending(directory,record3.correlationId)}await publishAdvisory(directory,record3,terminal.eventId,record3.normalizedAgent==="coder"?legacyTransferPending?"completed and settled; legacy coder settlement transfer is pending; durable reconciliation will retry":legacyTransferRequiresManualRecovery?"completed and settled; legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)":"completed and settled":"completed"),log(`[background] trusted completion settled: agent=${record3.normalizedAgent} task=${taskLabel(record3)} parent=${record3.parentSessionId}`)}catch(err){warn(`[background] completion observer error: ${err instanceof Error?err.message:String(err)}`)}},reconcilePending=async(record3)=>{if(replayInProgress)return!1;let terminal=record3.terminalResult;if(!terminal)return!1;replayInProgress=!0;try{await event({event:void 0,trustedTerminal:{record:record3,terminal,result:terminal.result,skipMaintenance:!0}});let refreshed=await findDelegationForCompletion(directory,record3.subagentSessionId);return refreshed?.record?refreshed.record.status==="consumed":!1}finally{replayInProgress=!1}};if(config3.enabled)registerLegacyCoderSettlementReconciler(directory,reconcilePending);return{event,reconcilePending,notifyLegacyCoderSettlementAdvisoryReplaced,prepareAdvisories:async(parentSessionId)=>{if(!config3.enabled||!parentSessionId)return null;let preparationId=`bg-prepare:${cryptoRandomId()}`,entries2=await preparePendingBackgroundAdvisories(directory,parentSessionId,{preparationId});return entries2.length===0?null:{preparationId,eventIds:entries2.map((entry)=>entry.eventId),messages:entries2.map((entry)=>entry.message)}},ackObservedAdvisories:(parentSessionId,observedTexts)=>acknowledgeObservedBackgroundAdvisories(directory,parentSessionId,observedTexts),releaseAdvisories:(parentSessionId,prepared)=>releasePreparedBackgroundAdvisories(directory,parentSessionId,prepared.preparationId,prepared.eventIds)}}async function transferLegacyCoderSettlement(directory,record3){if(!record3.planTaskId)return{disposition:"ok",outcome:"no task-scoped legacy settlement"};let transfer={taskId:record3.planTaskId,transitionId:`coder:${record3.callID}`},detail="unknown transfer failure",lastErrorCode=null;for(let attempt=0;attempt<3;attempt+=1)try{return{disposition:"ok",outcome:await observerInternals.transferCoderSettlementToBackground({directory,taskId:transfer.taskId,transitionId:transfer.transitionId})}}catch(error93){if(lastErrorCode=errorCode2(error93),detail=error93 instanceof Error?error93.message:String(error93),attempt===2||!isRetryableLegacyTransferErrorCode(lastErrorCode))break;await observerInternals.sleep(50*(attempt+1))}if(warn(`[background] legacy coder settlement transfer failed for ${record3.planTaskId}: ${detail}`),!isRetryableLegacyTransferErrorCode(lastErrorCode))return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"};let pending=null;for(let markerAttempt=0;markerAttempt<3;markerAttempt+=1){try{pending=await observerInternals.markLegacyCoderSettlementTransferPending(directory,record3.correlationId,transfer)}catch{pending=null}if(hasExactPendingLegacyTransfer(pending,transfer))break;if(markerAttempt<2)await observerInternals.sleep(50*(markerAttempt+1))}if(hasExactPendingLegacyTransfer(pending,transfer))return{disposition:"retry_pending",outcome:"legacy coder settlement transfer is pending; retrying durable reconciliation"};return{disposition:"manual_recovery",outcome:"legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session)"}}async function releaseCoderReservation(directory,record3,reason){if(!record3.coderReservationId)return;let bound=await bindBackgroundCoderReservation(directory,{reservationId:record3.coderReservationId,parentSessionId:record3.parentSessionId,planTaskId:record3.planTaskId,callID:record3.callID,correlationId:record3.correlationId});if(!bound){warn(`[background] coder reservation ${record3.coderReservationId} could not be bound for ${record3.correlationId}; admission remains fail-closed`);return}if(!await releaseBackgroundCoderReservation(directory,{...bound,generation:record3.generation??1,reason}))warn(`[background] coder reservation ${record3.coderReservationId} could not be released after ${reason}; the next admission will retry reconciliation`)}async function settleCoder(directory,record3,operationId){let context=record3.taskChangeContext;if(!context)return{ok:!1,record:record3,outcome:"stale: no coder baseline"};let claim=await claimCoderSettlement(directory,record3.correlationId,operationId);if(!claim)return{ok:!1,record:record3,outcome:"settlement claim failed"};if(claim.disposition==="settled")return{ok:!0,record:claim.record,outcome:"completed and settled"};if(claim.disposition==="preserved")return{ok:!1,record:claim.record,outcome:"settlement preserved"};if(record3=claim.record,!record3.worktree){let baseline=context.baseline,current=captureWorkspaceSnapshot(directory,{scope:baseline.scope,prHeadSha:baseline.prHeadSha,resolveCurrentPrHeadSha:baseline.prHeadSha!==null}),repositoryDelta=changedFilesSinceSnapshot(directory,baseline),declaredFiles=context.declaredFiles,observedFiles2=repositoryDelta&&declaredFiles&&declaredFiles.length>0?repositoryDelta.filter((file3)=>isInDeclaredScope(file3,declaredFiles,directory)):null,staleReason=!sameProjectRoot(baseline.directory,directory)?"shared-root directory identity changed":!baseline.gitHead||current.gitHead!==baseline.gitHead?"shared-root HEAD changed before coder completion":baseline.prHeadSha!==null&&current.prHeadSha!==baseline.prHeadSha?"shared-root PR head changed before coder completion":observedFiles2===null?"shared-root coder files could not be attributed to a non-empty declared scope":null;if(staleReason||observedFiles2===null){let preserved2=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"shared-root",result:"failed",reason:staleReason??"coder attribution failed"}});return await appendDelegationTransition(directory,record3.correlationId,{status:"stale"}),{ok:!1,record:preserved2??record3,outcome:`stale: ${staleReason??"coder attribution failed"}`}}let settled=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles:observedFiles2,outcome:{kind:"shared-root",result:"ready"}});return settled?{ok:!0,record:settled,outcome:"completed and settled"}:{ok:!1,record:record3,outcome:"settlement persistence failed"}}let descriptor=record3.worktree;if(descriptor.callID!==record3.callID||descriptor.parentSessionId!==record3.parentSessionId||descriptor.planTaskId!==record3.planTaskId||!sameProjectRoot(context.baseline.directory,descriptor.worktreePath))return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree recovery identity does not match the dispatch"}})??record3,outcome:"worktree settlement preserved: identity mismatch"};let observedFiles=changedFilesSinceSnapshot(descriptor.worktreePath,context.baseline);if(observedFiles===null)return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles:null,outcome:{kind:"standard-worktree",result:"failed",reason:"worktree files could not be attributed to the clean baseline"}})??record3,outcome:"worktree settlement preserved: attribution failed"};let dispatch=standardWorktreeByCallID.get(record3.callID)??{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID.delete(record3.callID),awaitingMergeByCallID.set(record3.callID,{callID:record3.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let resume=settlementResume(record3),mergeResult=await finishStandardWorktreeDispatch(directory,dispatch,void 0,record3.callID,{operationId,...resume?{resume}:{},onBeforeMerge:async(provenance)=>{let persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settling",sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore,observedFiles});if(!persisted)throw Error("could not persist pre-merge provenance");record3=persisted},onMerged:async(merged)=>{let provenance=merged.provenance??resume,persisted=await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"settled",observedFiles,...provenance?{sourceHeadAfterCommit:provenance.sourceHead,targetHeadBeforeMerge:provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:provenance&&provenance.sourceHead!==provenance.targetHeadBefore?"merged":"unchanged",sourceHeadAfterCommit:provenance?.sourceHead??null,targetHeadBeforeMerge:provenance?.targetHeadBefore??null,targetHeadAfterMerge:resolveCurrentGitHead(directory)}});if(!persisted)throw Error("could not persist merged settlement");record3=persisted}});if(mergeResult.outcome==="merged")return{ok:!0,record:(await findDelegationForCompletion(directory,record3.correlationId))?.record??record3,outcome:"completed and merged"};if(mergeResult.outcome==="failed"&&mergeResult.stage==="settlement-persist")return{ok:!1,record:record3,outcome:"worktree settlement persistence pending retry"};return{ok:!1,record:await updateCoderSettlement(directory,record3.correlationId,{operationId,state:"preserved",observedFiles,...mergeResult.provenance?{sourceHeadAfterCommit:mergeResult.provenance.sourceHead,targetHeadBeforeMerge:mergeResult.provenance.targetHeadBefore}:{},outcome:{kind:"standard-worktree",result:mergeResult.outcome,reason:mergeResult.message,sourceHeadAfterCommit:mergeResult.provenance?.sourceHead??null,targetHeadBeforeMerge:mergeResult.provenance?.targetHeadBefore??null}})??record3,outcome:`worktree settlement preserved: ${mergeResult.message}`}}function settlementResume(record3){let{coderSettlement:settlement,worktree}=record3;if(settlement?.state!=="settling"||!settlement.operationId||!settlement.sourceHeadAfterCommit||!settlement.targetHeadBeforeMerge||!GIT_OBJECT_ID_PATTERN.test(settlement.sourceHeadAfterCommit)||!GIT_OBJECT_ID_PATTERN.test(settlement.targetHeadBeforeMerge)||!worktree)return;return{operationId:settlement.operationId,sourceHead:settlement.sourceHeadAfterCommit,targetHeadBefore:settlement.targetHeadBeforeMerge,branchName:worktree.branchName,strategy:worktree.mergeStrategy}}async function publishAdvisory(directory,record3,eventId,outcome){let message=`[BACKGROUND COMPLETION ${eventId}] ${record3.normalizedAgent} task ${taskLabel(record3)} ${outcome}.`,input={eventId,parentSessionId:record3.parentSessionId,message},needsCorrection=!message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER),replacement=(needsCorrection?await replacePendingBackgroundAdvisory(directory,record3.correlationId,input):null)??null,stored=replacement?.advisory??await putPendingBackgroundAdvisory(directory,record3.correlationId,input);if(!stored)return;let session=swarmState.agentSessions.get(record3.parentSessionId);if(session){if(needsCorrection){if(removeQueuedLegacyTransferAdvisory(session.pendingAdvisoryMessages,eventId),replacement?.replacedMessage)removeQueuedAdvisoryMessage(session.pendingAdvisoryMessages,[replacement.replacedMessage])}pushAdvisory(session,stored.message)}}function errorCode2(error93){if(error93&&typeof error93==="object"&&"code"in error93&&typeof error93.code==="string")return error93.code??null;let detail=error93 instanceof Error?error93.message:String(error93);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}function hasExactPendingLegacyTransfer(record3,transfer){return record3?.legacyCoderSettlementTransfer?.taskId===transfer.taskId&&record3.legacyCoderSettlementTransfer.transitionId===transfer.transitionId}function isRetryableLegacyTransferErrorCode(code){return code!==null&&RETRYABLE_LEGACY_SETTLEMENT_TRANSFER_ERROR_CODES.has(code)}function removeQueuedAdvisoryMessage(queue,messagesToRemove){if(!queue||queue.length===0||messagesToRemove.length===0)return;let remove=new Set(messagesToRemove);for(let index=queue.length-1;index>=0;index-=1)if(remove.has(queue[index]))queue.splice(index,1)}function removeQueuedLegacyTransferAdvisory(queue,eventId){if(!queue||queue.length===0)return;let prefix=`[BACKGROUND COMPLETION ${eventId}]`;for(let index=queue.length-1;index>=0;index-=1){let message=queue[index];if(message?.startsWith(prefix)&&message.includes(LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER))queue.splice(index,1)}}function taskLabel(record3){return record3.evidenceTaskId??record3.planTaskId??"unknown"}function discardScopeForRecord(record3){let taskId=record3.evidenceTaskId??record3.planTaskId;if(!taskId)return;if(record3.normalizedAgent==="reviewer")discardReviewerScopeGenerationClaim({parentSessionID:record3.parentSessionId,taskId,reviewerCallID:record3.callID});else if(record3.normalizedAgent==="coder")discardReviewerScopeGenerationForCoderCall({parentSessionID:record3.parentSessionId,taskId,coderCallID:record3.callID})}function digest4(text){return createHash96("sha256").update(text).digest("hex")}function cryptoRandomId(){return createHash96("sha256").update(`${Date.now()}:${Math.random()}`).digest("hex").slice(0,24)}init_pr_subscriptions();init_commands();init_registry2();init_config();init_agent_model();init_bundled_skills();init_constants();init_config();init_package();init_constants();import*as fs152 from"node:fs";import*as path274 from"node:path";var CONFIG_SCHEMA_REF=`https://unpkg.com/opencode-swarm@${package_default.version}/opencode-swarm.schema.json`;function writeSwarmConfigExampleIfNew(projectDirectory){try{let swarmDir=path274.join(projectDirectory,".swarm"),dest=path274.join(swarmDir,"config.example.json");if(fs152.existsSync(dest))return;if(!fs152.existsSync(swarmDir))fs152.mkdirSync(swarmDir,{recursive:!0});let example={$schema:CONFIG_SCHEMA_REF,agents:Object.fromEntries(Object.entries(DEFAULT_MODELS).filter(([name])=>name!=="default").map(([name,model])=>[name,{model,fallback_models:["opencode/gpt-5-nano","opencode/big-pickle"]}])),max_iterations:5};fs152.writeFileSync(dest,`${JSON.stringify(example,null,2)}
7154
7154
  `,"utf-8")}catch{}}init_schema();init_schema();init_core_events();init_delegation_gate();init_utils2();init_injection_budget();init_utils();var FOR_TAG_PATTERN=/^\[FOR:\s*([^\]]+)\]/i;function containsPlanContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes(".swarm/plan")||lowerText.includes(".swarm/context")||lowerText.includes("swarm/plan.md")||lowerText.includes("swarm/context.md")}function containsKnowledgeContent(text){if(!text)return!1;let lowerText=text.toLowerCase();return lowerText.includes("knowledge")||lowerText.includes("lesson")||lowerText.includes(".swarm/knowledge")||lowerText.includes("swarm knowledge")}function parseForTag(content){let match=content.trim().match(FOR_TAG_PATTERN);if(!match)return null;let tagContent=match[1].trim();if(tagContent.toLowerCase()==="all")return["all"];return tagContent.split(",").map((agent)=>agent.trim().toLowerCase()).filter(Boolean)}function isTargetRoleAllowed(targetRole,allowedAgents){if(allowedAgents.includes("all"))return!0;let normalizedTarget=stripKnownSwarmPrefix(targetRole).toLowerCase();return allowedAgents.some((agent)=>{let normalizedAgent=stripKnownSwarmPrefix(agent).toLowerCase();return normalizedTarget===normalizedAgent})}function shouldNeverFilter(entry){if(entry.role==="system")return!0;if(entry.role==="user"){if(parseDelegationEnvelope(entry.content))return!0}if(entry.role==="assistant"){if(containsPlanContent(entry.content)||containsKnowledgeContent(entry.content))return!0}return!1}function logFilteringMetrics(directory,targetRole,totalEntries,includedEntries){try{appendCoreEventSync(directory,{event:"context_filtered",timestamp:new Date().toISOString(),agentName:targetRole,totalEntries,includedEntries,filteredEntries:totalEntries-includedEntries,estimatedTokensSaved:(totalEntries-includedEntries)*100})}catch(error93){log("[RoleFilter] event append failed",{error:error93 instanceof Error?error93.message:String(error93)})}}function filterByRole(entries2,targetRole,directory,options={}){if(!entries2||entries2.length===0)return[];let filtered=[];for(let entry of entries2){let allowedAgents=parseForTag(entry.content),canFilterTaggedSystem=entry.role==="system"&&options.filterTaggedSystem===!0&&allowedAgents!==null&&allowedAgents.length>0;if(shouldNeverFilter(entry)&&!canFilterTaggedSystem){filtered.push(entry);continue}if(allowedAgents===null){filtered.push(entry);continue}if(isTargetRoleAllowed(targetRole,allowedAgents))filtered.push(entry)}if(directory)logFilteringMetrics(directory,targetRole,entries2.length,filtered.length);return filtered}function createRoleFilterSystemHook(getActiveAgentName){return{"experimental.chat.system.transform":async(input,output)=>{if(!input.sessionID||!Array.isArray(output.system))return;let targetRole=input.agent??getActiveAgentName(input.sessionID);if(!targetRole)return;let entries2=output.system.map((content)=>({role:"system",content})),kept=filterByRole(entries2,targetRole,void 0,{filterTaggedSystem:!0}).map(({content})=>content),keptRemaining=new Map;for(let content of kept)keptRemaining.set(content,(keptRemaining.get(content)??0)+1);let removedTokens=0;for(let{content}of entries2){let remaining=keptRemaining.get(content)??0;if(remaining>0)keptRemaining.set(content,remaining-1);else removedTokens+=estimateTokens(content)}if(removedTokens>0)deductProducerEmission(input.sessionID,"system-enhancer",removedTokens,{expectedGeneration:input.expectedGeneration});output.system.length=0;for(let content of kept)output.system.push(content)}}}import*as fs155 from"node:fs";import*as path277 from"node:path";import*as fs154 from"node:fs";import*as path276 from"node:path";import*as crypto13 from"node:crypto";import*as fs153 from"node:fs";import*as path275 from"node:path";var _internals218={readFileSync:fs153.readFileSync,writeFileSync:fs153.writeFileSync,mkdirSync:fs153.mkdirSync,renameSync:fs153.renameSync,existsSync:fs153.existsSync,statSync:fs153.statSync,createHash:crypto13.createHash.bind(crypto13)};function computeContentHash3(content){return _internals218.createHash("sha256").update(content,"utf-8").digest("hex")}function createEmptyContextMap(){return{schema_version:1,generated_at:new Date().toISOString(),repo_fingerprint:"",files:{},task_history:{},decisions:[]}}function loadContextMap(directory){let filePath=path275.join(directory,".swarm","context-map.json");try{if(!_internals218.existsSync(filePath))return null;let raw=_internals218.readFileSync(filePath,"utf-8"),parsed=JSON.parse(raw);if(typeof parsed!=="object"||parsed===null||parsed.schema_version!==1)return null;return parsed}catch{return null}}function saveContextMap(map3,directory){let swarmDir=path275.join(directory,".swarm"),tmpPath=path275.join(swarmDir,"context-map.tmp"),finalPath=path275.join(swarmDir,"context-map.json");_internals218.mkdirSync(swarmDir,{recursive:!0});let updated={...map3,generated_at:new Date().toISOString()},json3=JSON.stringify(updated,null,2);_internals218.writeFileSync(tmpPath,json3,"utf-8"),_internals218.renameSync(tmpPath,finalPath)}function appendTaskHistory(map3,summary){return{...map3,task_history:{...map3.task_history,[summary.task_id]:summary}}}function appendDecision(map3,decision){return{...map3,decisions:[...map3.decisions,decision]}}var EXTENSION_LANGUAGE_MAP={".ts":"typescript",".tsx":"typescript",".js":"javascript",".jsx":"javascript",".mjs":"javascript",".py":"python",".rs":"rust",".go":"go",".json":"json",".md":"markdown",".yaml":"yaml",".yml":"yaml",".css":"css",".scss":"scss",".html":"html",".sh":"shell",".bash":"shell",".ps1":"powershell"};function detectLanguage(filePath){let ext=path276.extname(filePath).toLowerCase();return EXTENSION_LANGUAGE_MAP[ext]}var RE_EXPORT_NAMED=/export\s+(?:function|class|interface|type|const|let|var|enum)\s+(\w+)/g,RE_EXPORT_BRACE=/export\s*\{\s*([\w,\s]+)\s*\}/g,RE_IMPORT_FROM=/import\s+.*?\s+from\s+['"](.+?)['"]/g,RE_IMPORT_REQUIRE=/require\(\s*['"](.+?)['"]\s*\)/g,RE_FIRST_COMMENT=/\/\*(.+?)\*\//s,MAX_KEY_SYMBOLS=10,MAX_PURPOSE_LENGTH=200;function extractFileSummary(filePath,content,absolutePath2,existingEntry){let contentHash=computeContentHash3(content),language=detectLanguage(filePath),exportsList=extractExports(content),importsList=extractImports5(content),purpose=extractPurpose(content),keySymbols=exportsList.slice(0,MAX_KEY_SYMBOLS),mtimeMs=0;if(absolutePath2)try{mtimeMs=fs154.statSync(absolutePath2).mtimeMs}catch{}let base={path:filePath,content_hash:contentHash,mtime_ms:mtimeMs,language,purpose,exports:exportsList.length>0?exportsList:void 0,imports:importsList.length>0?importsList:void 0,key_symbols:keySymbols.length>0?keySymbols:void 0,summary:purpose};if(existingEntry)return{...base,invariants:existingEntry.invariants,risks:existingEntry.risks,tests:existingEntry.tests,last_seen_task_ids:existingEntry.last_seen_task_ids};return base}function isFileStale(entry,currentContent){let currentHash=computeContentHash3(currentContent);return entry.content_hash!==currentHash}function extractExports(content){let symbols2=[],namedRe=new RegExp(RE_EXPORT_NAMED.source,"g"),match;match=namedRe.exec(content);while(match!==null)symbols2.push(match[1]),match=namedRe.exec(content);let braceRe=new RegExp(RE_EXPORT_BRACE.source,"g");match=braceRe.exec(content);while(match!==null){let list=match[1];for(let name of list.split(",")){let trimmed=name.trim();if(trimmed)symbols2.push(trimmed)}match=braceRe.exec(content)}return symbols2}function extractImports5(content){let specifiers=[],fromRe=new RegExp(RE_IMPORT_FROM.source,"g"),match;match=fromRe.exec(content);while(match!==null)specifiers.push(match[1]),match=fromRe.exec(content);let requireRe=new RegExp(RE_IMPORT_REQUIRE.source,"g");match=requireRe.exec(content);while(match!==null)specifiers.push(match[1]),match=requireRe.exec(content);return specifiers}function extractPurpose(content){let match=RE_FIRST_COMMENT.exec(content);if(!match)return"No summary available";let body=match[1].split(`
7155
7155
  `).map((line)=>line.replace(/^\s*\*\s?/,"").trim()).join(" ").replace(/\s+/g," ").trim();if(body.length>MAX_PURPOSE_LENGTH)body=`${body.substring(0,MAX_PURPOSE_LENGTH)}...`;return body||"No summary available"}var decisionCounter=0;function nextDecisionId(){return decisionCounter+=1,`A${decisionCounter}`}function deriveFinalStatus(params){if(params.rejection_reasons&&params.rejection_reasons.length>0)return"rejected";switch(params.final_status){case"completed":return"approved";case"failed":return"rejected";case"blocked":return"blocked";case"cancelled":return"rejected"}}function readFileContent(absolutePath2){try{if(!_internals219.existsSync(absolutePath2))return null;return _internals219.readFileSync(absolutePath2,"utf-8")}catch{return null}}function refreshFileEntry(relativePath2,absolutePath2,existingEntry){let content=readFileContent(absolutePath2);if(content===null)return null;return _internals219.extractFileSummary(relativePath2,content,absolutePath2,existingEntry)}var _internals219={loadContextMap,saveContextMap,createEmptyContextMap,extractFileSummary,existsSync:fs155.existsSync,readFileSync:fs155.readFileSync,readdirSync:fs155.readdirSync,realpathSync:fs155.realpathSync,appendTaskHistory,appendDecision};function extractEvidenceFindings(taskId,directory){let result={rejection_reasons:[],review_findings:[]};try{let evidenceDir=path277.join(directory,".swarm","evidence",taskId);if(!_internals219.existsSync(evidenceDir))return result;let evidenceFiles=_internals219.readdirSync(evidenceDir),targetFiles=["evidence.json","reviewer.json","test-engineer.json","test_engineer.json"];for(let fileName of evidenceFiles){if(!targetFiles.includes(fileName))continue;let filePath=path277.join(evidenceDir,fileName),content=readFileContent(filePath);if(content===null)continue;try{let parsed=JSON.parse(content);if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed))continue;let obj=parsed;if(Array.isArray(obj.entries))for(let entry of obj.entries){if(typeof entry!=="object"||entry===null||Array.isArray(entry))continue;let entryObj=entry,entryType=String(entryObj.type??"").toLowerCase(),isActionable=entryType==="review"||entryType==="test"||entryType==="reviewer"||entryType==="test_engineer"||entryType==="test-engineer";if(isActionable&&typeof entryObj.verdict==="string"){let normalizedVerdict=String(entryObj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${entryObj.verdict}`)}if(isActionable){let entryIssues=entryObj.issues||entryObj.findings||[];if(Array.isArray(entryIssues))for(let issue3 of entryIssues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}let entryFailures=entryObj.failures;if(Array.isArray(entryFailures))for(let failure of entryFailures){let failureText=typeof failure==="object"&&failure!==null?String(failure.message||failure.detail||String(failure)):String(failure);if(failureText)result.review_findings.push(failureText)}}}else{if(typeof obj.verdict==="string"){let normalizedVerdict=String(obj.verdict).toLowerCase();if(normalizedVerdict==="rejected"||normalizedVerdict==="fail"||normalizedVerdict==="concerns")result.rejection_reasons.push(`[${fileName.replace(".json","")}] ${obj.verdict}`)}if(Array.isArray(obj.issues))for(let issue3 of obj.issues){let issueText=typeof issue3==="object"&&issue3!==null?String(issue3.message||issue3.detail||issue3.description||""):String(issue3);if(issueText)result.review_findings.push(issueText)}if(Array.isArray(obj.findings)){for(let finding of obj.findings)if(typeof finding==="object"&&finding!==null){let findingText=String(finding.message||finding.detail||finding.description||"");if(findingText)result.review_findings.push(findingText)}}}}catch{}}}catch{}return result}function updateContextMapAfterAgent(params){try{let map3=_internals219.loadContextMap(params.directory);if(map3===null)map3=_internals219.createEmptyContextMap();let root=path277.resolve(params.directory),updatedFiles={...map3.files},validFiles=[],realRoot=_internals219.realpathSync(root);for(let filePath of params.files_touched)try{let resolved=path277.resolve(root,filePath),realResolved=_internals219.realpathSync(resolved),relative62=path277.relative(realRoot,realResolved);if(relative62.startsWith("..")||path277.isAbsolute(relative62))continue;let normalizedRelative=relative62.replace(/\\/g,"/"),existingEntry=map3.files[normalizedRelative],refreshed=refreshFileEntry(normalizedRelative,resolved,existingEntry);if(refreshed!==null)updatedFiles[normalizedRelative]=refreshed;validFiles.push(normalizedRelative)}catch{}map3={...map3,files:updatedFiles};let evidenceFindings=extractEvidenceFindings(params.task_id,params.directory),rejectionReasons=params.rejection_reasons??[],reviewFindings=params.review_findings??[],mergedRejectionReasons=[...rejectionReasons,...evidenceFindings.rejection_reasons.filter((r)=>!rejectionReasons.includes(r))],mergedReviewFindings=[...reviewFindings,...evidenceFindings.review_findings.filter((f)=>!reviewFindings.includes(f))],reviewerFindings=[...mergedRejectionReasons.map((r)=>`[rejection] ${r}`),...mergedReviewFindings],taskSummary={task_id:params.task_id,goal:params.task_goal,files_touched:validFiles,implementation_summary:params.implementation_summary,reviewer_findings:reviewerFindings.length>0?reviewerFindings:void 0,final_status:mergedRejectionReasons.length>0?"rejected":deriveFinalStatus(params)};if(map3=_internals219.appendTaskHistory(map3,taskSummary),params.decisions)for(let entry of params.decisions){let decision={id:nextDecisionId(),decision:entry.decision,rationale:entry.rationale,timestamp:new Date().toISOString(),task_id:params.task_id};map3=_internals219.appendDecision(map3,decision)}return _internals219.saveContextMap(map3,params.directory),map3}catch{try{return _internals219.loadContextMap(params.directory)??_internals219.createEmptyContextMap()}catch{return _internals219.createEmptyContextMap()}}}init_dashboard();init_group_commit_writer();init_observability_event_store();init_project_db();init_spawn_circuit();init_coordination_store();init_logger();var TOKEN_BUCKET_NAMESPACE="dispatch.token-bucket",TOKEN_BUCKET_ENTITY_KEY="project",buckets=new Map;function refill(bucket,ratePerSecond,capacity,now2){if(now2<bucket.lastRefillMs)bucket.lastRefillMs=now2;let elapsedSeconds=(now2-bucket.lastRefillMs)/1000;if(elapsedSeconds>0&&ratePerSecond>0)bucket.level=Math.min(capacity,bucket.level+elapsedSeconds*ratePerSecond),bucket.lastRefillMs=now2}function persist(directory,bucket){try{let payload={level:bucket.level,lastRefillMs:bucket.lastRefillMs};transitionCoordinationState(directory,{namespace:TOKEN_BUCKET_NAMESPACE,entityKey:TOKEN_BUCKET_ENTITY_KEY,generation:1,status:"active",payload:JSON.stringify(payload)})}catch(err){_internals220.onPersistError(err)}}function hydrate(directory,capacity){let existing=buckets.get(directory);if(existing)return existing;let bucket={level:capacity,lastRefillMs:_internals220.now(),hydrated:!0};try{let row=_internals220.readState(directory);if(row){let parsed=JSON.parse(row.payload);if(typeof parsed.level==="number"&&Number.isFinite(parsed.level)){let nowMs3=_internals220.now();bucket={level:Math.min(capacity,Math.max(0,parsed.level)),lastRefillMs:typeof parsed.lastRefillMs==="number"&&Number.isFinite(parsed.lastRefillMs)?Math.min(parsed.lastRefillMs,nowMs3):nowMs3,hydrated:!0}}}}catch(err){_internals220.onPersistError(err)}return buckets.set(directory,bucket),bucket}async function acquireDispatchToken(input){let rate=input.ratePerSecond;if(!(rate>0))return;let capacity=Math.max(1,input.burstCapacity),bucket=hydrate(input.directory,capacity),waited=!1;for(;;){let now2=_internals220.now();if(refill(bucket,rate,capacity,now2),bucket.level>=1){if(bucket.level-=1,waited)persist(input.directory,bucket);return}waited=!0;let waitMs=Math.max(1,(1-bucket.level)/rate*1000);await _internals220.sleep(Math.min(waitMs,1000))}}var _internals220={now:()=>Date.now(),sleep:(ms)=>new Promise((resolve107)=>setTimeout(resolve107,ms)),readState:(directory)=>getCoordinationState(directory,TOKEN_BUCKET_NAMESPACE,TOKEN_BUCKET_ENTITY_KEY),onPersistError:(err)=>{if(process.env.DEBUG_SWARM)log("[dispatch.token-bucket] persist failed",err)}};init_model_dispatch_fallback();init_provider_error_classification();init_ephemeral_agent_dispatcher();function parseRequestedModel(modelId){if(modelId==="configured")return;let parsed=parseModelString2(modelId);if(!parsed)throw Error("explicit evaluation models must use provider/model syntax");return parsed}function resolveEvaluationAgentName(agents,logicalName,preferredSwarm){let names=agents.map((agent)=>agent.name);if(preferredSwarm){let preferred=`${preferredSwarm}_${logicalName}`;if(names.includes(preferred))return preferred;throw Error(`preferred swarm ${preferredSwarm} does not provide evaluation agent ${logicalName}`)}if(names.includes(logicalName))return logicalName;let prefixed=names.filter((name)=>name.endsWith(`_${logicalName}`)).sort((left,right)=>left.localeCompare(right));if(prefixed.length===1)return prefixed[0];if(prefixed.length>1)throw Error(`multiple swarms provide ${logicalName}; preferredSwarm is required`);throw Error(`evaluation agent ${logicalName} is not registered`)}var _internals221=Object.defineProperties({},{boundedAbort:{enumerable:!0,get:()=>_internals173.boundedAbort,set:(value)=>{_internals173.boundedAbort=value}},boundedDelete:{enumerable:!0,get:()=>_internals173.boundedDelete,set:(value)=>{_internals173.boundedDelete=value}},log:{enumerable:!0,get:()=>_internals173.log,set:(value)=>{_internals173.log=value}}});async function awaitWithAbort2(promise3,signal2){if(signal2.aborted)throw Error("evaluation dispatch aborted");return new Promise((resolve107,reject)=>{let onAbort=()=>reject(Error("evaluation dispatch aborted"));signal2.addEventListener("abort",onAbort,{once:!0}),promise3.then(resolve107,reject).finally(()=>{signal2.removeEventListener("abort",onAbort)})})}function createEvaluationModelDispatcher(client,pricing){return async(request)=>{let startedAt=Date.now();if(request.abortSignal?.aborted)return{status:"cancelled",modelId:request.modelId,text:"",durationMs:0};let resolvedAgentName,controller=new AbortController,timedOut=!1,abortListener=()=>controller.abort();request.abortSignal?.addEventListener("abort",abortListener,{once:!0});let timeoutHandle=setTimeout(()=>{timedOut=!0,controller.abort()},request.timeoutMs);try{let requestedModel=parseRequestedModel(request.modelId),agentsResult=await awaitWithAbort2(client.app.agents({query:{directory:request.sessionDirectory},signal:controller.signal}),controller.signal);if(!agentsResult.data)throw Error(`Failed to list registered evaluation agents: ${JSON.stringify(agentsResult.error)}`);resolvedAgentName=resolveEvaluationAgentName(agentsResult.data,request.agentName,request.preferredSwarm);let result=(await dispatchWithModelFallback({dispatch:async(_model,context)=>{let result2=await dispatchEphemeralAgent({client,directory:request.sessionDirectory,parentSessionId:request.parentSessionId,agentName:resolvedAgentName,model:requestedModel,...request.system===void 0?{}:{system:request.system},prompt:request.prompt,readOnlyTools:DEFAULT_READ_ONLY_TOOLS,title:`evaluation gate (${resolvedAgentName})`,timeoutMs:context.remainingMs??request.timeoutMs,abortSignal:controller.signal,pricing});if(result2.status==="completed")return result2;if(result2.status==="timeout")timedOut=!0;throw Error(result2.error??`evaluation dispatch ${result2.status}`)},classify:(error93)=>{let message=error93 instanceof Error?error93.message:String(error93);return isTransientProviderError(message)?"transient":"permanent"},maxTransientRetriesPerModel:2,backoffMs:()=>0,maxAttempts:3,deadlineAtMs:startedAt+request.timeoutMs})).result;return{status:"completed",modelId:result.modelId??request.modelId,agentName:resolvedAgentName,text:result.text,durationMs:Date.now()-startedAt,promptBytes:result.promptBytes,responseBytes:result.responseBytes,costFields:result.costFields}}catch(error93){let cancelled=request.abortSignal?.aborted===!0,msg=error93 instanceof Error?error93.message:String(error93),quotaMessage=isQuotaError(msg)?`${msg} (model quota/usage limit; retried the same model 2 time(s) — not substituted, to preserve benchmark attribution)`:msg;return{status:cancelled?"cancelled":timedOut?"timeout":"error",modelId:request.modelId,agentName:resolvedAgentName,text:"",durationMs:Date.now()-startedAt,error:quotaMessage}}finally{clearTimeout(timeoutHandle),request.abortSignal?.removeEventListener("abort",abortListener),controller.abort()}}}init_action_circuit();init_action_identity();init_invocation_failure();init_constants();init_schema();init_logger();init_oversight();init_state3();function configCadence(config3){let oversight=config3.full_auto?.oversight;return{everyToolCalls:oversight?.every_tool_calls??25,everyArchitectTurns:oversight?.every_architect_turns??5,everyMinutes:oversight?.every_minutes??20}}function denialLimits(config3){return{maxConsecutive:config3.full_auto?.denials?.max_consecutive??3,maxTotal:config3.full_auto?.denials?.max_total??20}}function evaluateFullAutoCadence(state2,config3,now2=Date.now()){let triggers=[],cadence=configCadence(config3),denials=denialLimits(config3);if(cadence.everyToolCalls>0&&state2.counters.toolCalls>0&&state2.counters.toolCalls%cadence.everyToolCalls===0)triggers.push({kind:"tool_calls",threshold:cadence.everyToolCalls});if(cadence.everyArchitectTurns>0&&state2.counters.architectTurns>0&&state2.counters.architectTurns%cadence.everyArchitectTurns===0)triggers.push({kind:"architect_turns",threshold:cadence.everyArchitectTurns});if(cadence.everyMinutes>0&&state2.lastOversightAt){let lastTs=Date.parse(state2.lastOversightAt);if(Number.isFinite(lastTs)){let elapsedMinutes=(now2-lastTs)/60000;if(elapsedMinutes>=cadence.everyMinutes)triggers.push({kind:"minutes",threshold:cadence.everyMinutes,elapsedMinutes})}}if(state2.counters.consecutiveNoProgressTurns>=3)triggers.push({kind:"consecutive_no_progress",threshold:3});if(denials.maxConsecutive>1&&state2.denialCounters.consecutive>=denials.maxConsecutive-1&&state2.denialCounters.consecutive<denials.maxConsecutive)triggers.push({kind:"denials_near_limit",consecutive:state2.denialCounters.consecutive,max:denials.maxConsecutive});return{shouldEscalate:triggers.length>0,triggers}}function tickAndEvaluate(directory,sessionID,counter,config3){let before=loadFullAutoRunState(directory,sessionID);if(!before||before.status!=="running")return;let updated=incrementFullAutoCounter(directory,sessionID,counter);if(!updated)return;return evaluateFullAutoCadence(updated,config3)}var cadenceDispatchInFlight=new Set;function resolveOversightAgentName2(activeAgent){if(!activeAgent)return"critic_oversight";if(stripKnownSwarmPrefix(activeAgent)!==ORCHESTRATOR_NAME)return"critic_oversight";let lastIdx=activeAgent.toLowerCase().lastIndexOf("architect");if(lastIdx>0)return`${activeAgent.slice(0,lastIdx)}critic_oversight`;return"critic_oversight"}function tickAndMaybeDispatchCadence(directory,sessionID,counter,config3,options={}){let decision=tickAndEvaluate(directory,sessionID,counter,config3);if(!decision||!decision.shouldEscalate)return decision;if(cadenceDispatchInFlight.has(sessionID))return decision;let runState=loadFullAutoRunState(directory,sessionID);if(!runState||runState.status!=="running")return decision;let oversightAgentName=resolveOversightAgentName2(options.activeAgent),criticModel=config3.full_auto?.critic_model??config3.agents?.critic?.model??"opencode/big-pickle";return cadenceDispatchInFlight.add(sessionID),(options.dispatch??dispatchFullAutoOversight)({directory,sessionID,trigger:`cadence:${decision.triggers.map((t)=>t.kind).join(",")}`,triggerSource:"cadence",phase:runState.currentPhase,taskID:runState.currentTaskID??void 0,planID:runState.planID,actionContext:{counters:runState.counters,denialCounters:runState.denialCounters,triggers:decision.triggers},criticModel,oversightAgentName,fullAutoConfig:{fail_closed:config3.full_auto?.fail_closed!==!1,max_dispatch_retries:config3.full_auto?.oversight?.max_dispatch_retries??2,max_consecutive_dispatch_failures:config3.full_auto?.oversight?.max_consecutive_dispatch_failures??3,total_timeout_ms:config3.full_auto?.oversight?.total_timeout_ms??120000}}).catch((err)=>{error48(`[full-auto/cadence] dispatch threw past dispatcher's own fail-closed branches: ${err instanceof Error?err.message:String(err)}`)}).finally(()=>{cadenceDispatchInFlight.delete(sessionID)}),decision}init_recovery2();init_severe_result();init_state3();init_task_file();init_invocation_failure();init_state2();init_utils();init_realtime_learning_nudge();init_utils2();import*as nodePath from"node:path";var MAX_TOOL_FAILURE_REASONS=5,MAX_TOOL_FAILURE_REASON_LENGTH=200;function extractFailureReason(error93){let raw;if(error93 instanceof Error)raw=error93.message;else if(typeof error93==="string")raw=error93;else if(error93&&typeof error93==="object"){let maybeMessage=error93.message;raw=typeof maybeMessage==="string"?maybeMessage:void 0}if(!raw)return;let trimmed=sanitizeFailureEvidenceDisplay(raw).trim();if(!trimmed)return;return trimmed.length>MAX_TOOL_FAILURE_REASON_LENGTH?`${trimmed.slice(0,MAX_TOOL_FAILURE_REASON_LENGTH)}...`:trimmed}function recordFailureReason(aggregate,reason){if(!aggregate.failureReasons)aggregate.failureReasons=[];if(aggregate.failureReasons.includes(reason))return;if(aggregate.failureReasons.length>=MAX_TOOL_FAILURE_REASONS)return;aggregate.failureReasons.push(reason)}function createAgentActivityHooks(config3,directory){if(config3.hooks?.agent_activity===!1)return{toolBefore:async()=>{},toolAfter:async()=>{}};return{toolBefore:async(input)=>{swarmState.activeToolCalls.set(input.callID,{tool:input.tool,sessionID:input.sessionID,callID:input.callID,startTime:Date.now()})},toolAfter:async(input,output)=>{let entry=swarmState.activeToolCalls.get(input.callID);if(!entry)return;swarmState.activeToolCalls.delete(input.callID);let duration5=Date.now()-entry.startTime,success3=!((typeof output.success==="boolean"?output.success:void 0)===!1||!!output.error),key2=entry.tool,existing=swarmState.toolAggregates.get(key2)??{tool:key2,count:0,successCount:0,failureCount:0,totalDuration:0};if(existing.count++,success3)existing.successCount++;else{existing.failureCount++;let reason=extractFailureReason(output.error);if(reason)recordFailureReason(existing,reason)}if(existing.totalDuration+=duration5,swarmState.toolAggregates.set(key2,existing),recordRealtimeLearningToolCall(entry.sessionID),swarmState.pendingEvents++,swarmState.pendingEvents>=20)flushActivityToFile(directory).catch((err)=>warn("Agent activity flush trigger failed:",err))}}}var flushPromise=null;async function flushActivityToFile(directory){if(flushPromise)return flushPromise=flushPromise.then(()=>doFlush(directory)).catch((err)=>{warn("Queued agent activity flush failed:",err)}),flushPromise;flushPromise=doFlush(directory);try{await flushPromise}finally{flushPromise=null}}async function doFlush(directory){try{let existing=await readSwarmFileAsync(directory,"context.md")??"",activitySection=renderActivitySection(),updated=replaceOrAppendSection(existing,"## Agent Activity",activitySection),flushedCount=swarmState.pendingEvents,path278=nodePath.join(directory,".swarm","context.md");await atomicWriteFile(path278,updated),swarmState.pendingEvents=Math.max(0,swarmState.pendingEvents-flushedCount)}catch(error93){warn("Agent activity flush failed:",error93)}}function renderActivitySection(){let lines=["## Agent Activity",""];if(swarmState.toolAggregates.size===0)return lines.push("No tool activity recorded yet."),lines.join(`
7156
7156
  `);lines.push("| Tool | Calls | Success | Failed | Avg Duration |"),lines.push("|------|-------|---------|--------|--------------|");let sorted2=[...swarmState.toolAggregates.values()].sort((a,b)=>b.count-a.count);for(let agg of sorted2){let avgDuration=agg.count>0?Math.round(agg.totalDuration/agg.count):0;lines.push(`| ${agg.tool} | ${agg.count} | ${agg.successCount} | ${agg.failureCount} | ${avgDuration}ms |`)}return lines.join(`
@@ -7622,7 +7622,7 @@ MICRO WORKED EXAMPLE:
7622
7622
  ${CANDIDATE_HEADERS.micro_lane}
7623
7623
  [CANDIDATE] | example-micro-001 | example-micro | MEDIUM | correctness | src/a.ts:12 | claim without pipes | invariant without pipes | evidence without pipes | HIGH
7624
7624
  Zero findings: ${CLEAN_TEMPLATES.micro_lane}
7625
- ${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;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error(`BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_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});cleanupAsyncLaunchSession(session,sessionId)}async function getLaneCollectionReadiness(session,directory,sessionId,deadline,hostTimeouts,statusBudgetMs){if(typeof session.status!=="function")return"unknown";if(statusBudgetMs<=0)return"unknown";try{let 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"};await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",result:idleLivenessResult,expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&&current.status!=="running"&&current.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),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(`
7625
+ ${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;if((gateState.prReviewBaseDispatches?.length??0)===0&&!stagedBaseDispatch){let ownedDimensionIds=parsed.data.lanes.flatMap((lane)=>lane.owned_workflow_lanes?.length?lane.owned_workflow_lanes:lane.workflow_lane?[lane.workflow_lane]:[]),coversAllSixExactlyOnce=ownedDimensionIds.length===PR_REVIEW_BASE_DIMENSION_IDS.length&&new Set(ownedDimensionIds).size===PR_REVIEW_BASE_DIMENSION_IDS.length&&PR_REVIEW_BASE_DIMENSION_IDS.every((dimensionId)=>ownedDimensionIds.includes(dimensionId));if(depthTier==="L"){if(parsed.data.lanes.length!==6||parsed.data.max_concurrent!==6||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error(`BLOCKED: initial PR_REVIEW base dispatch requires exactly six lanes and max_concurrent: 6 at depth tier L (consolidated owned_workflow_lanes are allowed only at tiers S and M); each lane owns exactly one dimension and may set workflow_lane to it, omitting owned_workflow_lanes; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}`)}else if(!coversAllSixExactlyOnce||parsed.data.lanes.length<PR_REVIEW_BASE_LANE_FLOORS[depthTier]||parsed.data.lanes.length>PR_REVIEW_BASE_DIMENSION_IDS.length||parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error(`BLOCKED: initial PR_REVIEW base dispatch at depth tier ${depthTier} requires between ${PR_REVIEW_BASE_LANE_FLOORS[depthTier]} and ${PR_REVIEW_BASE_DIMENSION_IDS.length} lanes whose owned_workflow_lanes partition all six dimensions exactly once, with max_concurrent equal to the lane count; valid dimensions: ${PR_REVIEW_BASE_DIMENSION_IDS.join(", ")}; a lane with one dimension may set workflow_lane to it and omit owned_workflow_lanes`)}if(stagedBaseDispatch){if(waveStage==="canary"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1||parsed.data.lanes.some((lane)=>(lane.owned_workflow_lanes?.length??1)!==1))throw Error("BLOCKED: PR_REVIEW staged base canary requires exactly one singleton lane and max_concurrent: 1")}else if(parsed.data.max_concurrent!==parsed.data.lanes.length)throw Error("BLOCKED: PR_REVIEW staged base fanout requires max_concurrent equal to the lane count")}for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW base lane "${lane.id}" must use the explorer role`);gateState=await enforcePrReviewBaseDimensions(directory,context.sessionID,laneSpecs,{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest,prReviewContractRetry:contractRetry,prReviewWaveStage:waveStage,prReviewWaveAttempt:waveAttempt,prReviewResiliencePolicy:effectiveResilience}),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:micro"){if(await assertPrReviewBaseCoverageSettled2(directory,context.sessionID),gateState.prHeadSha&&gateState.prHeadSha!==headSha)throw Error(`BLOCKED: PR_REVIEW head mismatch; expected "${gateState.prHeadSha}", received "${headSha}"`);for(let lane of parsed.data.lanes)if(resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames)!=="explorer")throw Error(`BLOCKED: PR_REVIEW micro lane "${lane.id}" must use the explorer role`);let effectiveTriggerEvaluation=parsed.data.trigger_evaluation!==void 0?parsed.data.trigger_evaluation:gateState.prReviewTriggerLedger;validatePrReviewMicroDispatch({...parsed.data,trigger_evaluation:effectiveTriggerEvaluation},depthTier),gateState=await bindPrReviewTriggerLedger(directory,context.sessionID,effectiveTriggerEvaluation),prReviewWorkflowInstanceId=gateState.workflowInstanceId,prReviewWorkflowRevision=gateState.revision}else if(parsed.data.mode==="swarm-pr-review:council"||parsed.data.mode==="swarm-pr-review:reviewer"||parsed.data.mode==="swarm-pr-review:critic"){let phase=parsed.data.mode.endsWith(":council")?"council":parsed.data.mode.endsWith(":reviewer")?"reviewer":"critic";if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to base and micro discovery lanes`);for(let lane of parsed.data.lanes){let role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames);if(phase==="council"&&!role.startsWith("council_")||phase==="reviewer"&&role!=="reviewer"||phase==="critic"&&!role.startsWith("critic"))throw Error(`BLOCKED: PR_REVIEW ${phase} lane "${lane.id}" uses invalid role "${role||lane.agent}"`)}await recordPrReviewValidationBatch(directory,context.sessionID,phase,laneSpecs,{batchId,prHeadSha:headSha})}else throw Error("BLOCKED: active PR_REVIEW requires a structured base, micro, council, reviewer, or critic mode")}else if(gateState?.mode==="PR_FEEDBACK"){let headSha=parsed.data.pr_head_sha;if(!headSha)throw Error("BLOCKED: PR_FEEDBACK dispatch requires pr_head_sha");if(parsed.data.lanes.some((lane)=>lane.owned_workflow_lanes))throw Error("BLOCKED: PR_FEEDBACK lanes must not declare owned_workflow_lanes; depth-tier consolidation applies only to PR_REVIEW base and micro discovery lanes");if(parsed.data.mode==="swarm-pr-feedback:verification")await declarePrFeedbackInventory(directory,context.sessionID,parsed.data.feedback_inventory??[],{prHeadSha:headSha}),await enforcePrFeedbackVerificationOwnership(directory,context.sessionID,parsed.data.lanes.map((lane)=>({laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]})),{batchId,prHeadSha:headSha});else if(parsed.data.mode==="swarm-pr-feedback:stage-b-reviewer"||parsed.data.mode==="swarm-pr-feedback:stage-b-test"||parsed.data.mode==="swarm-pr-feedback:closeout-reviewer"||parsed.data.mode==="swarm-pr-feedback:closeout-critic"){if(parsed.data.lanes.length!==1||parsed.data.max_concurrent!==1)throw Error("BLOCKED: each ordered PR_FEEDBACK gate requires exactly one lane and max_concurrent: 1");let phase=parsed.data.mode.slice(18),lane=parsed.data.lanes[0],role=resolveGeneratedAgentRole(lane.agent,swarmState.generatedAgentNames),expectedRole=phase==="stage-b-test"?"test_engineer":phase==="closeout-critic"?"critic":"reviewer";if(lane.workflow_lane!==phase||(expectedRole==="critic"?!role.startsWith("critic"):role!==expectedRole))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires workflow_lane "${phase}" and role "${expectedRole}"`);await recordPrFeedbackGateBatch(directory,context.sessionID,phase,{laneId:lane.id,ownedItemIds:lane.feedback_item_ids??[]},{batchId,prHeadSha:headSha,revisionDigest:workflowRevisionDigest??""})}else throw Error("BLOCKED: active PR_FEEDBACK requires structured verification, Stage B reviewer/test, and closeout reviewer/critic modes")}}catch(error93){return asyncFailureResult({failure_class:error93 instanceof PrReviewResilienceCircuitOpenError?"circuit_open":error93 instanceof PrReviewResilienceRetryExhaustedError?"retry_exhausted":"invalid_args",message:error93 instanceof Error?error93.message:"PR workflow gate rejected dispatch"})}let canonicalWorkflowScope=verifiedReviewBaseSha?`complete PR diff ${verifiedReviewBaseSha}...${verifiedPrHead}`:parsed.data.mode?.startsWith("swarm-pr-feedback:")?"the complete immutable feedback inventory on the exact checked-out revision":parsed.data.scope,maxConcurrent=Math.min(parsed.data.max_concurrent??lanes.length,lanes.length,MAX_LANES),launchTimeoutMs=parsed.data.launch_timeout_ms??parsed.data.timeout_ms??DEFAULT_ASYNC_LAUNCH_TIMEOUT_MS,dispatcher=_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});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"};await appendDelegationTransition(directory,currentAfterReadiness.correlationId,{status:"stale",result:idleLivenessResult,expectedCurrentStatuses:["pending","running","ingestion_error"]})}}function getCurrentStaleSweepCandidate(directory,record3,staleTimeoutMs,now2){let currentRead=findByCorrelationIdDetailed(directory,record3.correlationId);if(currentRead.status==="uncertain")return warnDelegationReadUncertainOnce2(`stale sweep skipped lane ${record3.laneId??record3.correlationId}`,currentRead),null;let current=currentRead.value;if(!current)return null;if(current.subagentSessionId!==record3.subagentSessionId)return null;if((current.generation??1)!==(record3.generation??1))return null;if(current.status!=="pending"&&current.status!=="running"&&current.status!=="ingestion_error")return null;if(now2-current.updatedAt<=staleTimeoutMs)return null;return current}var LANE_TERMINAL_REASON_MESSAGE_BUDGET=100;function laneTerminalErrorReason(error93){let message=error93.message.slice(0,LANE_TERMINAL_REASON_MESSAGE_BUDGET),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(`
7626
7626
 
7627
7627
  `),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(`
7628
7628
  `),footer=encodePrReviewCollectionReceiptFooter(record3,result,receipt)??encodePrReviewCollectionReceiptShedMarkerFromReceipt(record3,result,receipt);if(!footer)return null;let text=sanitizedPreview?`${sanitizedPreview}