opencode-swarm 7.171.0 → 7.171.1

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 (78) hide show
  1. package/binaries/win32-arm64/swarm-sandbox-runner.exe +0 -0
  2. package/binaries/win32-x64/swarm-sandbox-runner.exe +0 -0
  3. package/dist/cli/{coder-settlement-pn26zx36.js → coder-settlement-vxpmxk46.js} +7 -7
  4. package/dist/cli/{config-doctor-jrhpq41y.js → config-doctor-vwy3c9g9.js} +2 -2
  5. package/dist/cli/{core-r0nbh1k2.js → core-2znms60v.js} +1 -1
  6. package/dist/cli/{curation-policy-qemp257w.js → curation-policy-fakrpw5t.js} +4 -4
  7. package/dist/cli/{curator-drift-3ssjr0nx.js → curator-drift-r9r8gepb.js} +2 -2
  8. package/dist/cli/{curator-0g733bka.js → curator-kc80aj6d.js} +32 -32
  9. package/dist/cli/{curator-llm-factory-89yjg1m4.js → curator-llm-factory-exke3rag.js} +32 -32
  10. package/dist/cli/{evidence-summary-service-4r7sqb2h.js → evidence-summary-service-g3gr1pfs.js} +13 -13
  11. package/dist/cli/{gate-evidence-f13tm63x.js → gate-evidence-8mwsj2b7.js} +4 -4
  12. package/dist/cli/{guardrail-explain-kt4w2rt8.js → guardrail-explain-pkbjswtd.js} +33 -33
  13. package/dist/cli/{guardrail-log-18wdr04f.js → guardrail-log-qx1tpeda.js} +6 -6
  14. package/dist/cli/{guardrail-reset-795t6nah.js → guardrail-reset-v91p8ca6.js} +32 -32
  15. package/dist/cli/{hive-promoter-gwtvg5vc.js → hive-promoter-02vxb018.js} +32 -32
  16. package/dist/cli/{index-9fxnn8xg.js → index-0caqxnby.js} +1 -1
  17. package/dist/cli/{index-nmffafb0.js → index-2j0pd6sj.js} +32 -32
  18. package/dist/cli/{index-sz75avt3.js → index-3jcp3zb6.js} +1 -1
  19. package/dist/cli/{index-b3nw1bzp.js → index-3jwamrzw.js} +3 -3
  20. package/dist/cli/{index-sz9qnjd6.js → index-3zzyxs7q.js} +5 -5
  21. package/dist/cli/{index-dgpdnve5.js → index-4rq1d5k5.js} +2 -1
  22. package/dist/cli/{index-gxbesz2h.js → index-4sf357vj.js} +3 -3
  23. package/dist/cli/{index-yj0qrgyc.js → index-5134766r.js} +6 -6
  24. package/dist/cli/{index-003d071j.js → index-5vgd9st3.js} +6 -6
  25. package/dist/cli/{index-znf55hyt.js → index-6k5aq7b9.js} +2 -2
  26. package/dist/cli/{index-xdw0m34m.js → index-6mjtptnb.js} +1 -1
  27. package/dist/cli/{index-wp0396m1.js → index-7pae558g.js} +6 -6
  28. package/dist/cli/{index-4m7q9hqd.js → index-7qqwx64h.js} +5 -5
  29. package/dist/cli/{index-ak3ca0nv.js → index-8nbzfbjg.js} +5 -5
  30. package/dist/cli/{index-bvr0p6ns.js → index-95e3a9en.js} +1 -1
  31. package/dist/cli/{index-4dpsvbdt.js → index-9cp6bhx9.js} +3 -3
  32. package/dist/cli/{index-cravqkxf.js → index-9dz2ee2g.js} +55 -50
  33. package/dist/cli/{index-br3mvbsa.js → index-aa2eyfvr.js} +2 -2
  34. package/dist/cli/{index-ttyvcxxb.js → index-cdee25pp.js} +2 -2
  35. package/dist/cli/{index-zjkkz9qh.js → index-d5pk5b95.js} +2 -2
  36. package/dist/cli/{index-wy4txsws.js → index-d6bs0p6d.js} +7 -7
  37. package/dist/cli/{index-j92fe86t.js → index-dr1ym009.js} +9 -9
  38. package/dist/cli/{index-v3e19zzm.js → index-er6sk4e6.js} +1 -1
  39. package/dist/cli/{index-cex3emb2.js → index-evxd1art.js} +1 -1
  40. package/dist/cli/{index-bernkwgf.js → index-g6nen3gt.js} +1 -1
  41. package/dist/cli/{index-cgpwjctj.js → index-kb66he4e.js} +1 -1
  42. package/dist/cli/{index-k2cpsr0d.js → index-m1j1rth6.js} +1 -1
  43. package/dist/cli/{index-fdz0076x.js → index-nfs78aqj.js} +1 -1
  44. package/dist/cli/{index-g93g1c5r.js → index-rdjmbeex.js} +1 -1
  45. package/dist/cli/{index-d7yc4ys8.js → index-rkj71ej6.js} +3 -3
  46. package/dist/cli/{index-7s5cm87j.js → index-s7h6txsk.js} +2 -2
  47. package/dist/cli/{index-h17tpj0y.js → index-vs7b2pqm.js} +4 -4
  48. package/dist/cli/{index-7c0e181h.js → index-wn9gf91x.js} +1 -1
  49. package/dist/cli/{index-mvcjc28t.js → index-xefajbqv.js} +258 -175
  50. package/dist/cli/{index-0qa2cqyv.js → index-xm0131fx.js} +5 -5
  51. package/dist/cli/{index-dvbf6fpn.js → index-yqbnsmmv.js} +39 -0
  52. package/dist/cli/{index-npst1d4g.js → index-ztxh3nmf.js} +34 -34
  53. package/dist/cli/index.js +32 -32
  54. package/dist/cli/{knowledge-escalator-kpfm536v.js → knowledge-escalator-4j6xgcvj.js} +10 -10
  55. package/dist/cli/{knowledge-events-t3e721m2.js → knowledge-events-5ax1g356.js} +8 -8
  56. package/dist/cli/{knowledge-link-refyc1fz.js → knowledge-link-vh9pfnb9.js} +3 -3
  57. package/dist/cli/{knowledge-store-sk2bhh52.js → knowledge-store-2nrtfb5x.js} +4 -4
  58. package/dist/cli/{knowledge-validator-nmc56pbg.js → knowledge-validator-efcax8g9.js} +6 -6
  59. package/dist/cli/{pending-delegations-ckshrtar.js → pending-delegations-29qj2kya.js} +9 -9
  60. package/dist/cli/{pr-subscriptions-h81nme2p.js → pr-subscriptions-t51vcrvd.js} +9 -9
  61. package/dist/cli/{pr-workflow-gate-m1k4b8mr.js → pr-workflow-gate-03367gvd.js} +32 -32
  62. package/dist/cli/{runner-kzs5wbqh.js → runner-8m8qhngm.js} +4 -4
  63. package/dist/cli/{scan-cursor-e7varrte.js → scan-cursor-nhxpv6tj.js} +5 -5
  64. package/dist/cli/{schema-nsb0saad.js → schema-ht5hmsce.js} +1 -1
  65. package/dist/cli/{scope-persistence-2s5h5ry7.js → scope-persistence-6qebaksv.js} +13 -13
  66. package/dist/cli/{skill-generator-wpq9j1nf.js → skill-generator-tfm4kawf.js} +12 -12
  67. package/dist/cli/{snapshot-coordination-init-8nhmhefs.js → snapshot-coordination-init-zgfjjv9p.js} +32 -32
  68. package/dist/cli/{telemetry-z9scwfbz.js → telemetry-0mz37v3h.js} +1 -1
  69. package/dist/cli/{worktree-collision-ownership-2kmajcc9.js → worktree-collision-ownership-6mgm8p9g.js} +9 -9
  70. package/dist/cli/{worktree-isolation-kepgr7j2.js → worktree-isolation-02rr7t21.js} +32 -32
  71. package/dist/db/observability-event-store.d.ts +17 -1
  72. package/dist/index.js +17 -16
  73. package/dist/observability/index.d.ts +1 -1
  74. package/dist/observability/observe.d.ts +6 -0
  75. package/dist/pr-review/reducer.d.ts +18 -10
  76. package/dist/pr-review/types.d.ts +43 -47
  77. package/dist/telemetry.d.ts +10 -2
  78. package/package.json +2 -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.171.0",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","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:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.171.1",description:"Architect-centric agentic swarm plugin for OpenCode - hub-and-spoke orchestration with SME consultation, code generation, and QA review",main:"dist/index.js",types:"dist/index.d.ts",exports:{".":{types:"./dist/index.d.ts",default:"./dist/index.js"},"./package.json":"./package.json"},bin:{"opencode-swarm":"./dist/cli/index.js"},type:"module",engines:{bun:">=1.3.13",node:">=22.13"},license:"MIT",repository:{type:"git",url:"https://github.com/ZaxbyHub/opencode-swarm.git"},publishConfig:{access:"public",registry:"https://registry.npmjs.org/"},keywords:["opencode","opencode-plugin","ai","agents","orchestration","swarm","multi-agent","llm"],files:["dist","dist/lang/grammars","binaries","evaluation-fixtures",".opencode/skills/brainstorm",".opencode/skills/specify",".opencode/skills/clarify-spec",".opencode/skills/swarm-resume",".opencode/skills/clarify",".opencode/skills/discover",".opencode/skills/consult",".opencode/skills/pre-phase-briefing",".opencode/skills/council",".opencode/skills/deep-dive",".opencode/skills/deep-research",".opencode/skills/codebase-review-swarm",".opencode/skills/swarm-implement",".opencode/skills/design-docs",".opencode/skills/swarm-pr-review",".opencode/skills/swarm",".opencode/skills/swarm-pr-feedback",".opencode/skills/swarm-pr-subscribe",".opencode/skills/swarm-ci-monitor",".opencode/skills/issue-ingest",".opencode/skills/swarm-plan",".opencode/skills/critic-gate",".opencode/skills/execute",".opencode/skills/phase-wrap",".opencode/skills/loop",".opencode/skills/writing-tests",".opencode/skills/running-tests",".opencode/skills/engineering-conventions",".opencode/skills/commit-pr",".opencode/skills/ci-failure-batching",".opencode/skills/gate-attribution",".opencode/skills/merge-queue-readiness",".opencode/skills/skill-edit-validation",".opencode/skills/worktree-retry-cleanup",".opencode/skills/test-file-split",".opencode/skills/fork-pr-operations",".opencode/skills/parallel-work-check",".opencode/skills/ci-fix-monitor",".opencode/skills/issue-tracer",".opencode/skills/orchestrating-subagents",".opencode/skills/durable-session-state","tests/fixtures/memory-recall","tests/fixtures/memory-recall-heldout","opencode-swarm.schema.json","README.md","LICENSE"],scripts:{clean:`bun -e "require('fs').rmSync('dist',{recursive:true,force:true})"`,build:"bun run clean && bun run scripts/generate-config-schema.ts && bun run scripts/copy-grammars.ts && bun build src/index.ts --outdir dist --target node --format esm --external web-tree-sitter --minify-whitespace --minify-syntax && bun build src/cli/index.ts --outdir dist/cli --target bun --format esm --external bash-parser --splitting && bun run scripts/copy-grammars.ts --to-dist && tsc --emitDeclarationOnly",typecheck:"tsc --noEmit",test:"bun test",lint:"biome lint .","lint:ci":"biome ci .","test:unit:ci":"bun scripts/ci/run-unit-tests-local.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, and profile hash. Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately so you can keep working; launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted or false) while doing independent investigation, or join with wait: true when you need all results",agents:["architect"]},collect_lane_results:{description:"collect or poll results for a dispatch_lanes_async batch; a pure OBSERVER that never cancels or terminalizes child work unless you explicitly pass cancel_pending. Supports both non-blocking polling (wait omitted or false) and blocking join (wait: true). The wait budget bounds the observer call only — its expiry never kills a lane and is not evidence a lane died, so do not abort the workflow because a collection expired; poll again, cancel explicitly, or rely on the presumed-stale backstop. Any unsettled lane is reported in pending_lanes (batch_id, lane_id, stored status, output_ref when present) regardless of include_pending; busy/retry lanes are not timed out just because they run for a long time. Does not advance workflow gates. Inline output for a settled lane is delivered only once: later polls of the same lane set output_omitted_repeat: true and omit output, but still include output_ref for recovery via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -185,11 +185,11 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
185
185
  `),totalLines=lines.length,startLine=Math.max(0,offset);if(startLine>=totalLines)return{totalLines,startLine,endLine:totalLines,content:"",exhausted:!0};let endLine=Math.min(startLine+limit,totalLines);return{totalLines,startLine,endLine,content:lines.slice(startLine,endLine).join(`
186
186
  `),exhausted:!1}}function buildPreviewMarker(args2){let retrieval=args2.ref?` retrieve_lane_output ref=${args2.ref} for full output.`:" no full output artifact is available; treat this lane as degraded.";return`
187
187
  [... lane output preview omitted middle content.${args2.degraded?" Artifact storage degraded.":""}${retrieval} ...]
188
- `}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path10.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync3(path10.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync2(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync4(tempFile))try{unlinkSync2(tempFile)}catch{}}}function digestText(text){return createHash4("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});function batchDurabilityClass(classes){for(let cls of classes)if(cls==="full")return"full";return"normal"}function applySynchronousForClass(db,cls){db.run(cls==="full"?"PRAGMA synchronous = FULL;":"PRAGMA synchronous = NORMAL;")}function withDurabilityClass(db,cls,fn2){applySynchronousForClass(db,cls);try{return fn2()}finally{applySynchronousForClass(db,"normal")}}function withImmediateTransaction(db,cls,fn2,hooks={}){let owner=transactionOwners.get(db);if(owner){if(cls==="full"&&owner.durability!=="full")throw Error("Cannot nest a FULL coordination transaction inside a NORMAL owner");owner.depth+=1;try{return db.transaction(fn2)()}finally{owner.depth-=1}}if(db.inTransaction)throw Error("Refusing to nest inside an unknown non-coordination-owned transaction");hooks.beforeBegin?.(db),applySynchronousForClass(db,cls),transactionOwners.set(db,{durability:cls,depth:1}),db.run("BEGIN IMMEDIATE");let committed=!1;try{let result=fn2();return hooks.beforeOuterCommit?.(db),db.run("COMMIT"),committed=!0,hooks.afterOuterCommit?.(db),result}catch(err){if(!committed)try{db.run("ROLLBACK")}catch{}throw err}finally{transactionOwners.delete(db),applySynchronousForClass(db,"normal")}}var DURABILITY_CLASSES,transactionOwners;var init_durability=__esm(()=>{DURABILITY_CLASSES={qa_gate_profile:"full",qa_gate_profile_identity:"full",task_checkpoint_receipt:"full",coordination_event:"full",coordination_state:"full",coordination_lease:"full",coordination_import:"full",plan_ledger_event:"full",plan_ledger_state:"full",plan_ledger_import:"full",insight_candidate:"normal",phase_report:"normal",project_constraints:"normal",migration_failures:"normal",schema_migrations:"normal",observability_event:"normal",observability_sink_health:"normal",observability_import:"normal"};transactionOwners=new WeakMap});import*as fsSync4 from"node:fs";import*as path11 from"node:path";function normalizeIdentityPath2(resolved){let normalized=_internals10.platform()==="win32"?path11.win32.normalize(resolved):path11.posix.normalize(resolved);return _internals10.platform()==="win32"?normalized.replaceAll("\\","/").toLowerCase():normalized}function canonicalExistingFilesystemPath(entryPath){if(typeof entryPath!=="string")return null;let resolvedInput=path11.resolve(entryPath);try{return normalizeIdentityPath2(_internals10.realpathSyncNative(resolvedInput))}catch{try{return normalizeIdentityPath2(_internals10.realpathSync(resolvedInput))}catch{return null}}}function legacyCanonicalExistingFilesystemPath(entryPath){if(typeof entryPath!=="string")return null;try{return normalizeIdentityPath2(_internals10.realpathSync(path11.resolve(entryPath)))}catch{return null}}function appendLinkedAncestorWitnesses(witnesses,startPath){let probe=path11.resolve(startPath);for(let depth=0;depth<4096;depth++){let parent=path11.dirname(probe);if(parent===probe)return;probe=parent;try{if(!_internals10.lstatSync(probe).isSymbolicLink())continue}catch{continue}let canonical=canonicalExistingFilesystemPath(probe);if(canonical!==null)witnesses.push({lexicalPath:probe,canonicalPath:canonical})}}function filesystemIdentityWitnesses(entryPath){let lexicalPath=path11.resolve(entryPath),canonicalPath=canonicalExistingFilesystemPath(lexicalPath);if(canonicalPath===null)return[];let witnesses=[{lexicalPath,canonicalPath}];return appendLinkedAncestorWitnesses(witnesses,lexicalPath),witnesses}function canonicalPathFromExistingAncestor(entryPath){let probe=path11.resolve(entryPath),tail=[];for(let depth=0;depth<4096;depth++){let stat5;try{stat5=_internals10.lstatSync(probe)}catch(error49){let code=error49&&typeof error49==="object"&&"code"in error49?String(error49.code):void 0;if(code!=="ENOENT"&&code!=="ENOTDIR")return null;let parent=path11.dirname(probe);if(parent===probe)return null;tail.unshift(path11.basename(probe)),probe=parent;continue}let canonicalAncestor=canonicalExistingFilesystemPath(probe);if(canonicalAncestor===null)return null;let existingAncestorIsLink=!1;return existingAncestorIsLink=stat5.isSymbolicLink(),{canonicalPath:normalizeIdentityPath2(path11.join(canonicalAncestor,...tail)),existingAncestor:probe,existingAncestorIsLink,identityWitnesses:filesystemIdentityWitnesses(probe)}}return null}function canonicalPathForFutureIo(entryPath){return canonicalExistingFilesystemPath(entryPath)??canonicalPathFromExistingAncestor(entryPath)?.canonicalPath??null}function sameExistingFilesystemPath(a,b){let canonicalA=canonicalExistingFilesystemPath(a),canonicalB=canonicalExistingFilesystemPath(b);return canonicalA!==null&&canonicalB!==null&&canonicalA===canonicalB}var _internals10;var init_filesystem_identity=__esm(()=>{_internals10={realpathSyncNative:fsSync4.realpathSync.native,realpathSync:fsSync4.realpathSync,lstatSync:fsSync4.lstatSync,platform:()=>process.platform}});function classifyDbWriteError(err){let errno=err?.code;if(errno==="ENOSPC")return"disk_full";if(errno==="EACCES"||errno==="EROFS"||errno==="EPERM")return"read_only";let upper=(err instanceof Error?err.message:String(err)).toUpperCase();if(upper.includes("SQLITE_FULL")||upper.includes("DATABASE OR DISK IS FULL"))return"disk_full";if(upper.includes("SQLITE_READONLY")||upper.includes("ATTEMPT TO WRITE A READONLY"))return"read_only";if(upper.includes("SQLITE_CORRUPT")||upper.includes("DATABASE DISK IMAGE IS MALFORMED")||upper.includes("NOT A DATABASE"))return"corrupt";if(upper.includes("SQLITE_BUSY")||upper.includes("DATABASE IS LOCKED"))return"busy";return"unknown"}var ProjectDbError,DbWriteError;var init_db_errors=__esm(()=>{ProjectDbError=class ProjectDbError extends Error{category;constructor(category,message){super(message);this.name="ProjectDbError",this.category=category}};DbWriteError=class DbWriteError extends Error{category;constructor(category,message){super(message);this.name="DbWriteError",this.category=category}}});var exports_sqlite_loader={};__export(exports_sqlite_loader,{loadDatabaseCtor:()=>loadDatabaseCtor,createNodeDatabaseCtor:()=>createNodeDatabaseCtor,_internals:()=>_internals11});import{createRequire as createRequire2}from"node:module";function createNodeDatabaseCtor(DatabaseSyncCtor){class NodeSqliteDatabase{raw;stmts=new Map;savepointCounter=0;constructor(filename,options){let immutableReadOnly=typeof options==="number"&&(options&1)!==0&&(options&64)!==0&&filename.startsWith("file:"),readOnly=immutableReadOnly||typeof options==="object"&&options?.readonly===!0;this.raw=new DatabaseSyncCtor(immutableReadOnly?new URL(filename):filename,readOnly?{allowExtension:!1,readOnly:!0}:{allowExtension:!0})}statement(sql){let stmt=this.stmts.get(sql);if(!stmt)stmt=this.raw.prepare(sql),this.stmts.set(sql,stmt);return stmt}static CHANGES_PROBE_SQL="SELECT changes() AS c, last_insert_rowid() AS r";run(sql,...rest){if(rest.length===0){this.raw.exec(sql);let row=this.statement(NodeSqliteDatabase.CHANGES_PROBE_SQL).get();return{changes:Number(row?.c??0),lastInsertRowid:row?.r??0}}let params=rest.length===1&&Array.isArray(rest[0])?rest[0]:rest;return this.statement(sql).run(...params)}query(sql){let stmt=this.statement(sql);return{get:(...params)=>stmt.get(...params),all:(...params)=>stmt.all(...params),iterate:(...params)=>stmt.iterate(...params)}}prepare(sql){let stmt=this.raw.prepare(sql);return{get:(...params)=>stmt.get(...params),all:(...params)=>stmt.all(...params),iterate:(...params)=>stmt.iterate(...params),finalize:()=>{}}}get inTransaction(){return this.raw.isTransaction}transaction(fn2){return(...args2)=>{if(this.raw.isTransaction){let sp=`swarm_sp_${this.savepointCounter++}`;this.raw.exec(`SAVEPOINT ${sp}`);try{let result=fn2(...args2);return this.raw.exec(`RELEASE ${sp}`),result}catch(err){try{this.raw.exec(`ROLLBACK TO ${sp}`),this.raw.exec(`RELEASE ${sp}`)}catch{}throw err}}this.raw.exec("BEGIN");try{let result=fn2(...args2);return this.raw.exec("COMMIT"),result}catch(err){try{this.raw.exec("ROLLBACK")}catch{}throw err}}}loadExtension(path12){this.raw.enableLoadExtension(!0);try{this.raw.loadExtension(path12)}finally{this.raw.enableLoadExtension(!1)}}close(){this.stmts.clear(),this.raw.close()}}return NodeSqliteDatabase}function loadDatabaseCtor(){if(_DatabaseCtor)return _DatabaseCtor;let bunError;try{return _DatabaseCtor=_internals11.requireModule("bun:sqlite").Database,_DatabaseCtor}catch(err){bunError=err}try{let mod=_internals11.requireModule("node:sqlite"),nodeMajor=Number.parseInt(process.versions.node?.split(".")[0]??"0",10),nodeMinor=Number.parseInt(process.versions.node?.split(".")[1]??"0",10);if(Number.isFinite(nodeMajor)&&Number.isFinite(nodeMinor)&&(nodeMajor<22||nodeMajor===22&&nodeMinor<13))throw Error(`opencode-swarm: node:sqlite requires Node.js >= 22.13 (engines floor, issue #2480); this runtime is Node ${process.versions.node}. Upgrade Node or run under Bun >= 1.3.13.`);return _DatabaseCtor=createNodeDatabaseCtor(mod.DatabaseSync),_DatabaseCtor}catch(nodeError){let bunMsg=bunError instanceof Error?bunError.message:String(bunError),nodeMsg=nodeError instanceof Error?nodeError.message:String(nodeError);throw Error(`opencode-swarm: no SQLite driver available. This build needs Bun (bun:sqlite) or Node.js 22.13+ (node:sqlite). bun:sqlite: ${bunMsg}; node:sqlite: ${nodeMsg}`)}}var _DatabaseCtor=null,_internals11;var init_sqlite_loader=__esm(()=>{_internals11={requireModule(id){return createRequire2(import.meta.url)(id)},reset(){_DatabaseCtor=null}}});import{existsSync as existsSync5,mkdirSync as mkdirSync4,unlinkSync as unlinkSync3}from"node:fs";import{join as join8,resolve as resolve7}from"node:path";import{pathToFileURL}from"node:url";function lexicalAliasKey(directory){return lexicalRootAliasKey(directory)}function unbindAlias(alias,physicalKey){if(_projectDbAliases.get(alias)===physicalKey)_projectDbAliases.delete(alias);_projectDbs.get(physicalKey)?.aliases.delete(alias)}function bindAlias(record2,physicalKey,alias){let previousKey=_projectDbAliases.get(alias);if(previousKey!==void 0&&previousKey!==physicalKey)unbindAlias(alias,previousKey);record2.aliases.delete(alias),record2.aliases.add(alias),_projectDbAliases.set(alias,physicalKey);while(record2.aliases.size>MAX_ALIASES_PER_PROJECT_DB){let evicted=[...record2.aliases].find((candidate)=>candidate!==record2.primaryAlias&&candidate!==alias);if(evicted===void 0)break;unbindAlias(evicted,physicalKey)}}function closeRecord(physicalKey,record2){_internals12.checkpointWalBestEffort(record2.db),record2.db.close(),_projectDbs.delete(physicalKey);for(let alias of[...record2.aliases])unbindAlias(alias,physicalKey)}function recordMigrationFailure(db,migration,err,markerDir){let errorText=String(err instanceof Error?err.message:err).slice(0,MIGRATION_FAILURE_ERROR_MAX_CHARS);try{db.run("INSERT INTO migration_failures (version, name, error) VALUES (?, ?, ?)",[migration.version,migration.name,errorText]);return}catch{}if(!markerDir)return;try{atomicWriteSwarmFileSync(join8(markerDir,MIGRATION_FAILURE_MARKER),JSON.stringify({schema_version:1,version:migration.version,name:migration.name,error:errorText,failed_at:new Date().toISOString()},null,2))}catch{}}function removeMigrationFailureMarker(markerDir){let marker=join8(markerDir,MIGRATION_FAILURE_MARKER);if(!existsSync5(marker))return;try{unlinkSync3(marker)}catch{}}function isConcurrentMigrationApply(err){let msg=(err instanceof Error?err.message:String(err)).toLowerCase();if(msg.includes("unique constraint failed: schema_migrations"))return!0;return msg.includes("already exists")&&(msg.includes("table")||msg.includes("index")||msg.includes("trigger"))}function isSqliteBusy(err){let msg=(err instanceof Error?err.message:String(err)).toLowerCase();return msg.includes("sqlite_busy")||msg.includes("database is locked")||msg.includes("database is busy")}function isConcurrentOpenContention(err,dbPath){if(isSqliteBusy(err))return!0;return(err instanceof Error?err.message:String(err)).toLowerCase().includes("disk i/o error")&&existsSync5(dbPath)}function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let startedAt=Date.now();while(Date.now()-startedAt<ms);}}function currentVersionNowCovers(db,version2){return(db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0)>=version2}function currentVersionNowCoversSafely(db,version2){try{return currentVersionNowCovers(db,version2)}catch{return!1}}function runProjectMigrations(db,markerDir){db.run(`CREATE TABLE IF NOT EXISTS schema_migrations (
188
+ `}function laneOutputRelativePath(ref){let[,batchDigest,laneDigest,outputDigest]=ref.split(":");return path10.join("lane-results",batchDigest,laneDigest,`${outputDigest}.json`)}function hasValidArtifactIntegrity(artifact,expectedRef){let digest=digestText(artifact.text);if(artifact.digest!==digest)return!1;if(artifact.chars!==artifact.text.length)return!1;if(artifact.bytes!==Buffer.byteLength(artifact.text,"utf-8"))return!1;let batchDigest=digestText(artifact.batchId),laneDigest=digestText(artifact.laneId),expectedArtifactRef=`${LANE_OUTPUT_REF_PREFIX}:${batchDigest}:${laneDigest}:${digest}`;return artifact.ref===expectedRef&&artifact.ref===expectedArtifactRef}function artifactIdentityMatchesInput(artifact,input){return artifact.agent===input.agent&&artifact.role===input.role&&artifact.sessionId===input.sessionId&&artifact.parentSessionId===input.parentSessionId&&artifact.mode===input.mode&&artifact.workflowLane===input.workflowLane&&artifact.prHeadSha===input.prHeadSha&&artifact.gitHead===input.gitHead&&artifact.revisionDigest===input.revisionDigest&&artifact.scope===input.scope&&artifact.source===input.source}function writeAtomicJson(absPath,value){mkdirSync3(path10.dirname(absPath),{recursive:!0});let tempFile=`${absPath}.tmp-${Date.now()}-${process.pid}`;try{writeFileSync(tempFile,JSON.stringify(value,null,2),"utf-8");let lastRenameError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES2;attempt++)try{renameSync2(tempFile,absPath),lastRenameError=void 0;break}catch(err){lastRenameError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break}if(lastRenameError)throw lastRenameError}finally{if(existsSync4(tempFile))try{unlinkSync2(tempFile)}catch{}}}function digestText(text){return createHash4("sha256").update(text).digest("hex")}var LANE_OUTPUT_REF_PREFIX="L1",MAX_LANE_OUTPUT_STORED_BYTES=10485760,LANE_OUTPUT_SCHEMA_VERSION=1,REF_RE,LaneOutputArtifactSchema,WINDOWS_RENAME_MAX_RETRIES2=3;var init_lane_output_store=__esm(()=>{init_zod();init_utils2();REF_RE=/^L1:[a-f0-9]{64}:[a-f0-9]{64}:[a-f0-9]{64}$/,LaneOutputArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(LANE_OUTPUT_SCHEMA_VERSION),ref:exports_external.string().regex(REF_RE),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),agent:exports_external.string().min(1),role:exports_external.string().min(1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),mode:exports_external.string().min(1).optional(),workflowLane:exports_external.string().min(1).optional(),prHeadSha:exports_external.string().min(1).optional(),gitHead:exports_external.string().min(1).optional(),revisionDigest:exports_external.string().min(1).optional(),scope:exports_external.string().min(1).optional(),source:exports_external.enum(["dispatch_lanes","collect_lane_results"]),text:exports_external.string(),chars:exports_external.number().int().nonnegative(),bytes:exports_external.number().int().nonnegative(),digest:exports_external.string().regex(/^[a-f0-9]{64}$/),messageCount:exports_external.number().int().nonnegative().optional(),transcriptIncomplete:exports_external.boolean().optional(),createdAt:exports_external.string(),updatedAt:exports_external.string()}).strict()});function batchDurabilityClass(classes){for(let cls of classes)if(cls==="full")return"full";return"normal"}function applySynchronousForClass(db,cls){db.run(cls==="full"?"PRAGMA synchronous = FULL;":"PRAGMA synchronous = NORMAL;")}function withDurabilityClass(db,cls,fn2){applySynchronousForClass(db,cls);try{return fn2()}finally{applySynchronousForClass(db,"normal")}}function withImmediateTransaction(db,cls,fn2,hooks={}){let owner=transactionOwners.get(db);if(owner){if(cls==="full"&&owner.durability!=="full")throw Error("Cannot nest a FULL coordination transaction inside a NORMAL owner");owner.depth+=1;try{return db.transaction(fn2)()}finally{owner.depth-=1}}if(db.inTransaction)throw Error("Refusing to nest inside an unknown non-coordination-owned transaction");hooks.beforeBegin?.(db),applySynchronousForClass(db,cls),transactionOwners.set(db,{durability:cls,depth:1}),db.run("BEGIN IMMEDIATE");let committed=!1;try{let result=fn2();return hooks.beforeOuterCommit?.(db),db.run("COMMIT"),committed=!0,hooks.afterOuterCommit?.(db),result}catch(err){if(!committed)try{db.run("ROLLBACK")}catch{}throw err}finally{transactionOwners.delete(db),applySynchronousForClass(db,"normal")}}var DURABILITY_CLASSES,transactionOwners;var init_durability=__esm(()=>{DURABILITY_CLASSES={qa_gate_profile:"full",qa_gate_profile_identity:"full",task_checkpoint_receipt:"full",coordination_event:"full",coordination_state:"full",coordination_lease:"full",coordination_import:"full",plan_ledger_event:"full",plan_ledger_state:"full",plan_ledger_import:"full",insight_candidate:"normal",phase_report:"normal",project_constraints:"normal",migration_failures:"normal",schema_migrations:"normal",observability_event:"normal",observability_sink_health:"normal",observability_import:"normal"};transactionOwners=new WeakMap});import*as fsSync4 from"node:fs";import*as path11 from"node:path";function normalizeIdentityPath2(resolved){let normalized=_internals10.platform()==="win32"?path11.win32.normalize(resolved):path11.posix.normalize(resolved);return _internals10.platform()==="win32"?normalized.replaceAll("\\","/").toLowerCase():normalized}function canonicalExistingFilesystemPath(entryPath){if(typeof entryPath!=="string")return null;let resolvedInput=path11.resolve(entryPath);try{return normalizeIdentityPath2(_internals10.realpathSyncNative(resolvedInput))}catch{try{return normalizeIdentityPath2(_internals10.realpathSync(resolvedInput))}catch{return null}}}function legacyCanonicalExistingFilesystemPath(entryPath){if(typeof entryPath!=="string")return null;try{return normalizeIdentityPath2(_internals10.realpathSync(path11.resolve(entryPath)))}catch{return null}}function appendLinkedAncestorWitnesses(witnesses,startPath){let probe=path11.resolve(startPath);for(let depth=0;depth<4096;depth++){let parent=path11.dirname(probe);if(parent===probe)return;probe=parent;try{if(!_internals10.lstatSync(probe).isSymbolicLink())continue}catch{continue}let canonical=canonicalExistingFilesystemPath(probe);if(canonical!==null)witnesses.push({lexicalPath:probe,canonicalPath:canonical})}}function filesystemIdentityWitnesses(entryPath){let lexicalPath=path11.resolve(entryPath),canonicalPath=canonicalExistingFilesystemPath(lexicalPath);if(canonicalPath===null)return[];let witnesses=[{lexicalPath,canonicalPath}];return appendLinkedAncestorWitnesses(witnesses,lexicalPath),witnesses}function canonicalPathFromExistingAncestor(entryPath){let probe=path11.resolve(entryPath),tail=[];for(let depth=0;depth<4096;depth++){let stat5;try{stat5=_internals10.lstatSync(probe)}catch(error49){let code=error49&&typeof error49==="object"&&"code"in error49?String(error49.code):void 0;if(code!=="ENOENT"&&code!=="ENOTDIR")return null;let parent=path11.dirname(probe);if(parent===probe)return null;tail.unshift(path11.basename(probe)),probe=parent;continue}let canonicalAncestor=canonicalExistingFilesystemPath(probe);if(canonicalAncestor===null)return null;let existingAncestorIsLink=!1;return existingAncestorIsLink=stat5.isSymbolicLink(),{canonicalPath:normalizeIdentityPath2(path11.join(canonicalAncestor,...tail)),existingAncestor:probe,existingAncestorIsLink,identityWitnesses:filesystemIdentityWitnesses(probe)}}return null}function canonicalPathForFutureIo(entryPath){return canonicalExistingFilesystemPath(entryPath)??canonicalPathFromExistingAncestor(entryPath)?.canonicalPath??null}function sameExistingFilesystemPath(a,b){let canonicalA=canonicalExistingFilesystemPath(a),canonicalB=canonicalExistingFilesystemPath(b);return canonicalA!==null&&canonicalB!==null&&canonicalA===canonicalB}var _internals10;var init_filesystem_identity=__esm(()=>{_internals10={realpathSyncNative:fsSync4.realpathSync.native,realpathSync:fsSync4.realpathSync,lstatSync:fsSync4.lstatSync,platform:()=>process.platform}});function classifyDbWriteError(err){let errno=err?.code;if(errno==="ENOSPC")return"disk_full";if(errno==="EACCES"||errno==="EROFS"||errno==="EPERM")return"read_only";let upper=(err instanceof Error?err.message:String(err)).toUpperCase();if(upper.includes("SQLITE_FULL")||upper.includes("DATABASE OR DISK IS FULL"))return"disk_full";if(upper.includes("SQLITE_READONLY")||upper.includes("ATTEMPT TO WRITE A READONLY"))return"read_only";if(upper.includes("SQLITE_CORRUPT")||upper.includes("DATABASE DISK IMAGE IS MALFORMED")||upper.includes("NOT A DATABASE"))return"corrupt";if(upper.includes("SQLITE_BUSY")||upper.includes("DATABASE IS LOCKED"))return"busy";return"unknown"}var ProjectDbError,DbWriteError;var init_db_errors=__esm(()=>{ProjectDbError=class ProjectDbError extends Error{category;constructor(category,message){super(message);this.name="ProjectDbError",this.category=category}};DbWriteError=class DbWriteError extends Error{category;constructor(category,message){super(message);this.name="DbWriteError",this.category=category}}});var exports_sqlite_loader={};__export(exports_sqlite_loader,{loadDatabaseCtor:()=>loadDatabaseCtor,createNodeDatabaseCtor:()=>createNodeDatabaseCtor,_internals:()=>_internals11});import{createRequire as createRequire2}from"node:module";function createNodeDatabaseCtor(DatabaseSyncCtor){class NodeSqliteDatabase{raw;stmts=new Map;savepointCounter=0;constructor(filename,options){let immutableReadOnly=typeof options==="number"&&(options&1)!==0&&(options&64)!==0&&filename.startsWith("file:"),readOnly=immutableReadOnly||typeof options==="object"&&options?.readonly===!0;this.raw=new DatabaseSyncCtor(immutableReadOnly?new URL(filename):filename,readOnly?{allowExtension:!1,readOnly:!0}:{allowExtension:!0})}statement(sql){let stmt=this.stmts.get(sql);if(!stmt)stmt=this.raw.prepare(sql),this.stmts.set(sql,stmt);return stmt}static CHANGES_PROBE_SQL="SELECT changes() AS c, last_insert_rowid() AS r";run(sql,...rest){if(rest.length===0){this.raw.exec(sql);let row=this.statement(NodeSqliteDatabase.CHANGES_PROBE_SQL).get();return{changes:Number(row?.c??0),lastInsertRowid:row?.r??0}}let params=rest.length===1&&Array.isArray(rest[0])?rest[0]:rest;return this.statement(sql).run(...params)}query(sql){let stmt=this.statement(sql);return{get:(...params)=>stmt.get(...params),all:(...params)=>stmt.all(...params),iterate:(...params)=>stmt.iterate(...params)}}prepare(sql){let stmt=this.raw.prepare(sql);return{get:(...params)=>stmt.get(...params),all:(...params)=>stmt.all(...params),iterate:(...params)=>stmt.iterate(...params),finalize:()=>{}}}get inTransaction(){return this.raw.isTransaction}transaction(fn2){return(...args2)=>{if(this.raw.isTransaction){let sp=`swarm_sp_${this.savepointCounter++}`;this.raw.exec(`SAVEPOINT ${sp}`);try{let result=fn2(...args2);return this.raw.exec(`RELEASE ${sp}`),result}catch(err){try{this.raw.exec(`ROLLBACK TO ${sp}`),this.raw.exec(`RELEASE ${sp}`)}catch{}throw err}}this.raw.exec("BEGIN");try{let result=fn2(...args2);return this.raw.exec("COMMIT"),result}catch(err){try{this.raw.exec("ROLLBACK")}catch{}throw err}}}loadExtension(path12){this.raw.enableLoadExtension(!0);try{this.raw.loadExtension(path12)}finally{this.raw.enableLoadExtension(!1)}}close(){this.stmts.clear(),this.raw.close()}}return NodeSqliteDatabase}function loadDatabaseCtor(){if(_DatabaseCtor)return _DatabaseCtor;let bunError;try{return _DatabaseCtor=_internals11.requireModule("bun:sqlite").Database,_DatabaseCtor}catch(err){bunError=err}try{let mod=_internals11.requireModule("node:sqlite"),nodeMajor=Number.parseInt(process.versions.node?.split(".")[0]??"0",10),nodeMinor=Number.parseInt(process.versions.node?.split(".")[1]??"0",10);if(Number.isFinite(nodeMajor)&&Number.isFinite(nodeMinor)&&(nodeMajor<22||nodeMajor===22&&nodeMinor<13))throw Error(`opencode-swarm: node:sqlite requires Node.js >= 22.13 (engines floor, issue #2480); this runtime is Node ${process.versions.node}. Upgrade Node or run under Bun >= 1.3.13.`);return _DatabaseCtor=createNodeDatabaseCtor(mod.DatabaseSync),_DatabaseCtor}catch(nodeError){let bunMsg=bunError instanceof Error?bunError.message:String(bunError),nodeMsg=nodeError instanceof Error?nodeError.message:String(nodeError);throw Error(`opencode-swarm: no SQLite driver available. This build needs Bun (bun:sqlite) or Node.js 22.13+ (node:sqlite). bun:sqlite: ${bunMsg}; node:sqlite: ${nodeMsg}`)}}var _DatabaseCtor=null,_internals11;var init_sqlite_loader=__esm(()=>{_internals11={requireModule(id){return createRequire2(import.meta.url)(id)},reset(){_DatabaseCtor=null}}});import{existsSync as existsSync5,mkdirSync as mkdirSync4,unlinkSync as unlinkSync3}from"node:fs";import{join as join8,resolve as resolve7}from"node:path";import{pathToFileURL}from"node:url";function lexicalAliasKey(directory){return lexicalRootAliasKey(directory)}function unbindAlias(alias,physicalKey){if(_projectDbAliases.get(alias)===physicalKey)_projectDbAliases.delete(alias);_projectDbs.get(physicalKey)?.aliases.delete(alias)}function bindAlias(record2,physicalKey,alias){let previousKey=_projectDbAliases.get(alias);if(previousKey!==void 0&&previousKey!==physicalKey)unbindAlias(alias,previousKey);record2.aliases.delete(alias),record2.aliases.add(alias),_projectDbAliases.set(alias,physicalKey);while(record2.aliases.size>MAX_ALIASES_PER_PROJECT_DB){let evicted=[...record2.aliases].find((candidate)=>candidate!==record2.primaryAlias&&candidate!==alias);if(evicted===void 0)break;unbindAlias(evicted,physicalKey)}}function closeRecord(physicalKey,record2){_internals12.checkpointWalBestEffort(record2.db),record2.db.close(),_projectDbs.delete(physicalKey);for(let alias of[...record2.aliases])unbindAlias(alias,physicalKey)}function recordMigrationFailure(db,migration,err,markerDir){let errorText=String(err instanceof Error?err.message:err).slice(0,MIGRATION_FAILURE_ERROR_MAX_CHARS);try{db.run("INSERT INTO migration_failures (version, name, error) VALUES (?, ?, ?)",[migration.version,migration.name,errorText]);return}catch{}if(!markerDir)return;try{atomicWriteSwarmFileSync(join8(markerDir,MIGRATION_FAILURE_MARKER),JSON.stringify({schema_version:1,version:migration.version,name:migration.name,error:errorText,failed_at:new Date().toISOString()},null,2))}catch{}}function removeMigrationFailureMarker(markerDir){let marker=join8(markerDir,MIGRATION_FAILURE_MARKER);if(!existsSync5(marker))return;try{unlinkSync3(marker)}catch{}}function isConcurrentMigrationApply(err){let msg=(err instanceof Error?err.message:String(err)).toLowerCase();if(msg.includes("unique constraint failed: schema_migrations"))return!0;return msg.includes("already exists")&&(msg.includes("table")||msg.includes("index")||msg.includes("trigger"))}function isDuplicateColumn(err){return(err instanceof Error?err.message:String(err)).toLowerCase().includes("duplicate column name")}function alterColumnAlreadyApplied(db,migration){let matches=[...migration.sql.trim().matchAll(/ALTER\s+TABLE\s+(\w+)\s+ADD\s+COLUMN\s+(\w+)/gi)];if(matches.length===0)return!1;try{for(let match of matches)if(!db.query(`PRAGMA table_info(${match[1]})`).all().some((c)=>c.name===match[2]))return!1;return!0}catch{return!1}}function isSqliteBusy(err){let msg=(err instanceof Error?err.message:String(err)).toLowerCase();return msg.includes("sqlite_busy")||msg.includes("database is locked")||msg.includes("database is busy")}function isConcurrentOpenContention(err,dbPath){if(isSqliteBusy(err))return!0;return(err instanceof Error?err.message:String(err)).toLowerCase().includes("disk i/o error")&&existsSync5(dbPath)}function sleepSync(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let startedAt=Date.now();while(Date.now()-startedAt<ms);}}function currentVersionNowCovers(db,version2){return(db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0)>=version2}function currentVersionNowCoversSafely(db,version2){try{return currentVersionNowCovers(db,version2)}catch{return!1}}function runProjectMigrations(db,markerDir){db.run(`CREATE TABLE IF NOT EXISTS schema_migrations (
189
189
  version INTEGER PRIMARY KEY,
190
190
  name TEXT NOT NULL,
191
191
  applied_at TEXT NOT NULL DEFAULT (datetime('now'))
192
- )`);let currentVersion=db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0;for(let migration of MIGRATIONS){if(migration.version<=currentVersion)continue;let apply=db.transaction(()=>{db.run(migration.sql),db.run("INSERT INTO schema_migrations (version, name) VALUES (?, ?)",[migration.version,migration.name])}),lastError;for(let attempt=0;attempt<=MIGRATION_BUSY_RETRIES;attempt+=1)try{apply(),lastError=void 0;break}catch(err){if(lastError=err,currentVersionNowCoversSafely(db,migration.version)){lastError=void 0;break}if(!isSqliteBusy(err)||attempt===MIGRATION_BUSY_RETRIES)break;sleepSync(10*(attempt+1))}if(lastError!==void 0){let err=lastError;if(isConcurrentMigrationApply(err)&&currentVersionNowCoversSafely(db,migration.version))continue;throw recordMigrationFailure(db,migration,err,markerDir),new ProjectDbError("migration_failed",`swarm.db migration v${migration.version} (${migration.name}) failed: ${err instanceof Error?err.message:String(err)}`)}}if(markerDir)removeMigrationFailureMarker(markerDir)}function projectDbPath(directory){return join8(canonicalRootKeyFresh(directory),".swarm","swarm.db")}function projectDbExists(directory){return existsSync5(projectDbPath(directory))}function withProjectDbReadOnly(directory,read){let cached2=_projectDbs.get(canonicalRootKeyFresh(directory));if(cached2)return read(cached2.db);let dbFile=projectDbPath(directory);if(!existsSync5(dbFile))return null;let Db=loadDatabaseCtor(),db=existsSync5(`${dbFile}-wal`)?new Db(dbFile,{readonly:!0}):(()=>{let immutableUrl=pathToFileURL(dbFile);return immutableUrl.searchParams.set("immutable","1"),new Db(immutableUrl.href,65)})();try{return read(db)}finally{db.close()}}function checkpointWalBestEffort(db){try{let row=db.query("PRAGMA wal_checkpoint(TRUNCATE)").get();if(row&&row.busy===1)db.run("PRAGMA wal_checkpoint(PASSIVE);")}catch{try{db.run("PRAGMA wal_checkpoint(PASSIVE);")}catch{}}}function getProjectDb(directory){let materializedDirectory=resolve7(directory);try{mkdirSync4(materializedDirectory,{recursive:!0})}catch(err){throw new ProjectDbError("mkdir_failed",`Failed to create project root ${materializedDirectory}: ${err instanceof Error?err.message:String(err)}`)}let key=canonicalRootKeyFresh(materializedDirectory),alias=lexicalAliasKey(directory),existing=_projectDbs.get(key);if(existing)return bindAlias(existing,key,alias),existing.db;let swarmDir=join8(key,".swarm");try{mkdirSync4(swarmDir,{recursive:!0})}catch(err){throw new ProjectDbError("mkdir_failed",`Failed to create .swarm/ for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let db;try{let Db;try{Db=loadDatabaseCtor()}catch(err){throw new ProjectDbError("driver_unavailable",`Failed to resolve a SQLite driver for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let dbFile=join8(swarmDir,"swarm.db");for(let attempt=0;attempt<=OPEN_CONTENTION_RETRIES;attempt+=1){db=new Db(dbFile);try{db.run("PRAGMA busy_timeout = 5000;"),db.run("PRAGMA journal_mode = WAL;"),db.run("PRAGMA synchronous = NORMAL;"),db.run("PRAGMA foreign_keys = ON;"),runProjectMigrations(db,swarmDir);break}catch(err){try{db.close()}catch{}if(db=void 0,!isConcurrentOpenContention(err,dbFile)||attempt===OPEN_CONTENTION_RETRIES)throw err;sleepSync(25*(attempt+1))}}if(!db)throw Error("SQLite initialization exhausted its busy retry budget")}catch(err){if(db)try{db.close()}catch{}if(err instanceof ProjectDbError)throw err;throw new ProjectDbError("open_failed",`Failed to open .swarm/swarm.db for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let record2={db,primaryAlias:alias,aliases:new Set};return _projectDbs.set(key,record2),bindAlias(record2,key,alias),db}function closeProjectDb(directory){let alias=lexicalAliasKey(directory);if(canonicalExistingFilesystemPath(directory)!==null){let currentKey=canonicalRootKeyFresh(directory),currentRecord=_projectDbs.get(currentKey);if(currentRecord)closeRecord(currentKey,currentRecord);return}let previousKey=_projectDbAliases.get(alias),previousRecord=previousKey===void 0?void 0:_projectDbs.get(previousKey);if(previousKey!==void 0&&previousRecord)closeRecord(previousKey,previousRecord)}function closeAllProjectDbs(){for(let record2 of _projectDbs.values())try{checkpointWalBestEffort(record2.db),record2.db.close()}catch{}_projectDbs.clear(),_projectDbAliases.clear()}var MIGRATION_FAILURE_ERROR_MAX_CHARS=500,MIGRATION_FAILURE_MARKER="db-migration-failure.json",MIGRATION_BUSY_RETRIES=2,OPEN_CONTENTION_RETRIES=4,MIGRATIONS,_projectDbs,_projectDbAliases,MAX_ALIASES_PER_PROJECT_DB=128,_internals12;var init_project_db=__esm(()=>{init_atomic_write();init_canonical_root();init_filesystem_identity();init_db_errors();init_sqlite_loader();MIGRATIONS=[{version:1,name:"create_project_constraints",sql:`CREATE TABLE project_constraints (
192
+ )`);let currentVersion=db.query("SELECT MAX(version) as version FROM schema_migrations").get()?.version??0;for(let migration of MIGRATIONS){if(migration.version<=currentVersion)continue;let apply=db.transaction(()=>{db.run(migration.sql),db.run("INSERT INTO schema_migrations (version, name) VALUES (?, ?)",[migration.version,migration.name])}),lastError;for(let attempt=0;attempt<=MIGRATION_BUSY_RETRIES;attempt+=1)try{apply(),lastError=void 0;break}catch(err){if(lastError=err,currentVersionNowCoversSafely(db,migration.version)){lastError=void 0;break}if(!isSqliteBusy(err)||attempt===MIGRATION_BUSY_RETRIES)break;sleepSync(10*(attempt+1))}if(lastError!==void 0){let err=lastError;if(isConcurrentMigrationApply(err)&&currentVersionNowCoversSafely(db,migration.version))continue;if(isDuplicateColumn(err)&&alterColumnAlreadyApplied(db,migration)){db.run("INSERT INTO schema_migrations (version, name) VALUES (?, ?)",[migration.version,migration.name]);continue}throw recordMigrationFailure(db,migration,err,markerDir),new ProjectDbError("migration_failed",`swarm.db migration v${migration.version} (${migration.name}) failed: ${err instanceof Error?err.message:String(err)}`)}}if(markerDir)removeMigrationFailureMarker(markerDir)}function projectDbPath(directory){return join8(canonicalRootKeyFresh(directory),".swarm","swarm.db")}function projectDbExists(directory){return existsSync5(projectDbPath(directory))}function withProjectDbReadOnly(directory,read){let cached2=_projectDbs.get(canonicalRootKeyFresh(directory));if(cached2)return read(cached2.db);let dbFile=projectDbPath(directory);if(!existsSync5(dbFile))return null;let Db=loadDatabaseCtor(),db=existsSync5(`${dbFile}-wal`)?new Db(dbFile,{readonly:!0}):(()=>{let immutableUrl=pathToFileURL(dbFile);return immutableUrl.searchParams.set("immutable","1"),new Db(immutableUrl.href,65)})();try{return read(db)}finally{db.close()}}function checkpointWalBestEffort(db){try{let row=db.query("PRAGMA wal_checkpoint(TRUNCATE)").get();if(row&&row.busy===1)db.run("PRAGMA wal_checkpoint(PASSIVE);")}catch{try{db.run("PRAGMA wal_checkpoint(PASSIVE);")}catch{}}}function getProjectDb(directory){let materializedDirectory=resolve7(directory);try{mkdirSync4(materializedDirectory,{recursive:!0})}catch(err){throw new ProjectDbError("mkdir_failed",`Failed to create project root ${materializedDirectory}: ${err instanceof Error?err.message:String(err)}`)}let key=canonicalRootKeyFresh(materializedDirectory),alias=lexicalAliasKey(directory),existing=_projectDbs.get(key);if(existing)return bindAlias(existing,key,alias),existing.db;let swarmDir=join8(key,".swarm");try{mkdirSync4(swarmDir,{recursive:!0})}catch(err){throw new ProjectDbError("mkdir_failed",`Failed to create .swarm/ for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let db;try{let Db;try{Db=loadDatabaseCtor()}catch(err){throw new ProjectDbError("driver_unavailable",`Failed to resolve a SQLite driver for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let dbFile=join8(swarmDir,"swarm.db");for(let attempt=0;attempt<=OPEN_CONTENTION_RETRIES;attempt+=1){db=new Db(dbFile);try{db.run("PRAGMA busy_timeout = 5000;"),db.run("PRAGMA journal_mode = WAL;"),db.run("PRAGMA synchronous = NORMAL;"),db.run("PRAGMA foreign_keys = ON;"),runProjectMigrations(db,swarmDir);break}catch(err){try{db.close()}catch{}if(db=void 0,!isConcurrentOpenContention(err,dbFile)||attempt===OPEN_CONTENTION_RETRIES)throw err;sleepSync(25*(attempt+1))}}if(!db)throw Error("SQLite initialization exhausted its busy retry budget")}catch(err){if(db)try{db.close()}catch{}if(err instanceof ProjectDbError)throw err;throw new ProjectDbError("open_failed",`Failed to open .swarm/swarm.db for project ${key}: ${err instanceof Error?err.message:String(err)}`)}let record2={db,primaryAlias:alias,aliases:new Set};return _projectDbs.set(key,record2),bindAlias(record2,key,alias),db}function closeProjectDb(directory){let alias=lexicalAliasKey(directory);if(canonicalExistingFilesystemPath(directory)!==null){let currentKey=canonicalRootKeyFresh(directory),currentRecord=_projectDbs.get(currentKey);if(currentRecord)closeRecord(currentKey,currentRecord);return}let previousKey=_projectDbAliases.get(alias),previousRecord=previousKey===void 0?void 0:_projectDbs.get(previousKey);if(previousKey!==void 0&&previousRecord)closeRecord(previousKey,previousRecord)}function closeAllProjectDbs(){for(let record2 of _projectDbs.values())try{checkpointWalBestEffort(record2.db),record2.db.close()}catch{}_projectDbs.clear(),_projectDbAliases.clear()}var MIGRATION_FAILURE_ERROR_MAX_CHARS=500,MIGRATION_FAILURE_MARKER="db-migration-failure.json",MIGRATION_BUSY_RETRIES=2,OPEN_CONTENTION_RETRIES=4,MIGRATIONS,_projectDbs,_projectDbAliases,MAX_ALIASES_PER_PROJECT_DB=128,_internals12;var init_project_db=__esm(()=>{init_atomic_write();init_canonical_root();init_filesystem_identity();init_db_errors();init_sqlite_loader();MIGRATIONS=[{version:1,name:"create_project_constraints",sql:`CREATE TABLE project_constraints (
193
193
  id INTEGER PRIMARY KEY AUTOINCREMENT,
194
194
  constraint_type TEXT NOT NULL,
195
195
  content TEXT NOT NULL,
@@ -422,7 +422,8 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
422
422
  imported_at TEXT NOT NULL DEFAULT (datetime('now'))
423
423
  )`},{version:36,name:"create_plan_ledger_event_indexes",sql:`CREATE INDEX IF NOT EXISTS idx_plan_ledger_event_plan
424
424
  ON plan_ledger_event(plan_id, seq)`},{version:37,name:"create_plan_ledger_import_hash_index",sql:`CREATE INDEX IF NOT EXISTS idx_plan_ledger_import_hash
425
- ON plan_ledger_import(source_hash)`}],_projectDbs=new Map,_projectDbAliases=new Map;_internals12={checkpointWalBestEffort,projectDbCount:()=>_projectDbs.size,projectDbAliasCount:()=>_projectDbAliases.size}});import{createHash as createHash5}from"node:crypto";function boundedText(value,label,max){if(value.length===0||value.length>max)throw Error(`${label} must contain 1..${max} characters`);return value}function validatePayload(payload){return boundedText(payload,"payload",MAX_PAYLOAD_CHARS),JSON.parse(payload),payload}function digestPayload(payload){return createHash5("sha256").update(payload,"utf8").digest("hex")}function rowToState(row){if(!row)return null;return validatePayload(row.payload),{namespace:row.namespace,entityKey:row.entity_key,revision:row.revision,generation:row.generation,status:row.status,payload:row.payload,updatedAt:row.updated_at}}function readState(db,namespace,entityKey){let row=db.query(`SELECT namespace, entity_key, revision, generation, status, payload, updated_at
425
+ ON plan_ledger_import(source_hash)`},{version:38,name:"add_observability_event_line_hash",sql:"ALTER TABLE observability_event ADD COLUMN line_hash TEXT"},{version:39,name:"create_observability_event_line_hash_index",sql:`CREATE INDEX IF NOT EXISTS idx_obs_event_line_hash
426
+ ON observability_event(line_hash)`}],_projectDbs=new Map,_projectDbAliases=new Map;_internals12={checkpointWalBestEffort,projectDbCount:()=>_projectDbs.size,projectDbAliasCount:()=>_projectDbAliases.size}});import{createHash as createHash5}from"node:crypto";function boundedText(value,label,max){if(value.length===0||value.length>max)throw Error(`${label} must contain 1..${max} characters`);return value}function validatePayload(payload){return boundedText(payload,"payload",MAX_PAYLOAD_CHARS),JSON.parse(payload),payload}function digestPayload(payload){return createHash5("sha256").update(payload,"utf8").digest("hex")}function rowToState(row){if(!row)return null;return validatePayload(row.payload),{namespace:row.namespace,entityKey:row.entity_key,revision:row.revision,generation:row.generation,status:row.status,payload:row.payload,updatedAt:row.updated_at}}function readState(db,namespace,entityKey){let row=db.query(`SELECT namespace, entity_key, revision, generation, status, payload, updated_at
426
427
  FROM coordination_state WHERE namespace = ? AND entity_key = ?`).get(namespace,entityKey)??null;return rowToState(row)}function transactionHooks(){return{beforeBegin:(db)=>_internals13.coordinationFaultInjector?.("before_begin",db),beforeOuterCommit:(db)=>_internals13.coordinationFaultInjector?.("before_outer_commit",db)}}function withCoordinationTransaction(directory,fn2){return withImmediateTransaction(getProjectDb(directory),DURABILITY_CLASSES.coordination_state,fn2,transactionHooks())}function getCoordinationState(directory,namespace,entityKey){if(!projectDbExists(directory))return null;return readState(getProjectDb(directory),namespace,entityKey)}function listCoordinationStates(directory,namespace,limit=5000){if(!projectDbExists(directory))return[];let boundedLimit=Number.isFinite(limit)?Math.max(0,Math.min(MAX_COORDINATION_STATE_LIST_ROWS,Math.trunc(limit))):0;if(boundedLimit===0)return[];let db=getProjectDb(directory),states=[],lastEntityKey;while(states.length<boundedLimit){let pageLimit=Math.min(COORDINATION_STATE_PAGE_SIZE,boundedLimit-states.length),rows=lastEntityKey===void 0?db.query(`SELECT namespace, entity_key, revision, generation, status, payload, updated_at
427
428
  FROM coordination_state WHERE namespace = ? ORDER BY entity_key LIMIT ?`).all(namespace,pageLimit):db.query(`SELECT namespace, entity_key, revision, generation, status, payload, updated_at
428
429
  FROM coordination_state
@@ -465,7 +466,7 @@ ${trimmed}`}else malformedRows++;continue}let rowFields=fields.slice(0,CANDIDATE
465
466
  lease_expires_at = excluded.lease_expires_at, payload = excluded.payload,
466
467
  updated_at = excluded.updated_at`,[input.namespace,input.entityKey,input.generation,input.ownerToken,input.leaseExpiresAt,input.payload,now]),{outcome:"acquired"}})}function releaseCoordinationLease(directory,namespace,entityKey,generation,ownerToken){return withCoordinationTransaction(directory,()=>{return getProjectDb(directory).run(`DELETE FROM coordination_lease
467
468
  WHERE namespace = ? AND entity_key = ? AND generation = ? AND owner_token = ?`,[namespace,entityKey,generation,ownerToken]).changes===1})}function importCoordinationOnce(directory,input,importer){if(boundedText(input.source,"source",MAX_KEY_CHARS),boundedText(input.sourceDigest,"sourceDigest",MAX_KEY_CHARS),boundedText(input.emptyNamespace,"emptyNamespace",MAX_KEY_CHARS),!Number.isSafeInteger(input.rowCount)||input.rowCount<0)throw Error("rowCount must be a nonnegative safe integer");let result=withCoordinationTransaction(directory,()=>{let db=getProjectDb(directory);if(db.query("SELECT 1 AS present FROM coordination_import WHERE source = ?").get(input.source))return"already_imported";if((db.query("SELECT COUNT(*) AS count FROM coordination_state WHERE namespace = ?").get(input.emptyNamespace)?.count??0)!==0)return"state_exists";return importer(),db.run(`INSERT INTO coordination_import
468
- (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:260"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:644",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:648",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:652",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:690",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:738",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:920",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:928",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:953",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:656",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:666",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:786",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1823",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:771",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:785",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:699",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:716",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:703",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:726",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1097",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:742",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:761",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1330",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:799",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:808",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:812",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:908",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:916",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:938",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:826",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:847",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:861",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:878",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:895",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1311",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:968",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:982",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:995",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1009",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:348",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1587",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1046",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1068",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1112",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1149",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1175",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1199",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1222",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1251",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1295",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),line=JSON.stringify(_internals15.toLegacyTelemetryLine(canonical))+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},trainingVaultHealth(data){_internals15.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
469
+ (source, imported_at, source_digest, row_count) VALUES (?, ?, ?, ?)`,[input.source,new Date().toISOString(),input.sourceDigest,input.rowCount]),"imported"});if(result==="imported")_internals13.coordinationFaultInjector?.("after_commit_before_archive",getProjectDb(directory));return result}function deleteCoordinationImports(directory,sources){let boundedSources=sources.map((source)=>boundedText(source,"source",MAX_KEY_CHARS));if(boundedSources.length===0||!projectDbExists(directory))return 0;return withCoordinationTransaction(directory,()=>{let placeholders=boundedSources.map(()=>"?").join(", ");return getProjectDb(directory).run(`DELETE FROM coordination_import WHERE source IN (${placeholders})`,boundedSources).changes})}var MAX_KEY_CHARS=512,MAX_STATUS_CHARS=128,MAX_PAYLOAD_CHARS=1048576,MAX_EVENTS_PER_STREAM=2048,MAX_TOTAL_EVENTS=1e5,MAX_EVENT_FENCES_PER_STREAM=8192,MAX_TOTAL_EVENT_FENCES=400000,MAX_COORDINATION_STATE_LIST_ROWS=25000,COORDINATION_STATE_PAGE_SIZE=5000,_internals13;var init_coordination_store=__esm(()=>{init_durability();init_project_db();_internals13={maxEventsPerStream:MAX_EVENTS_PER_STREAM,maxTotalEvents:MAX_TOTAL_EVENTS,maxEventFencesPerStream:MAX_EVENT_FENCES_PER_STREAM,maxTotalEventFences:MAX_TOTAL_EVENT_FENCES}});import*as crypto2 from"node:crypto";import*as fs6 from"node:fs";import*as path12 from"node:path";function getLockFilePath(directory,filePath){let normalized=path12.resolve(directory,filePath),baseDir=path12.resolve(directory)+path12.sep;if(!(process.platform==="win32"?normalized.toLowerCase().startsWith(baseDir.toLowerCase()):normalized.startsWith(baseDir)))throw Error("Invalid file path: path traversal not allowed");let pathForHash=process.platform==="win32"?normalized.toLowerCase():normalized,hash2=crypto2.createHash("sha256").update(pathForHash).digest("hex"),lockPath=path12.join(directory,LOCKS_DIR,`${hash2}.lock`),legacyPaths=[pathForHash];if(process.platform==="win32"&&normalized!==pathForHash)legacyPaths.push(normalized);for(let legacyPath of legacyPaths){let oldHash=Buffer.from(legacyPath).toString("base64").replace(/[/+=]/g,"_"),oldLockPath=path12.join(directory,LOCKS_DIR,`${oldHash}.lock`);if(fs6.existsSync(oldLockPath))return oldLockPath}return lockPath}function getMetaPath(lockPath){return`${lockPath.replace(/\.lock$/,"")}.meta`}async function writeMetaFile(metaPath,metadata){let tmpPath=`${metaPath}.tmp`;try{await _internals14.writeFile(tmpPath,JSON.stringify(metadata),"utf-8"),await fs6.promises.rename(tmpPath,metaPath)}catch(err){try{await fs6.promises.unlink(tmpPath)}catch{}throw err}}function readMetaFile(metaPath){try{let content=fs6.readFileSync(metaPath,"utf-8");return JSON.parse(content)}catch{return null}}async function tryAcquireLock(directory,filePath,agent,taskId){let lockPath=getLockFilePath(directory,filePath),locksDir=path12.dirname(lockPath);if(!fs6.existsSync(locksDir))fs6.mkdirSync(locksDir,{recursive:!0});if(!fs6.existsSync(lockPath))fs6.writeFileSync(lockPath,"","utf-8");let release;try{release=await import_proper_lockfile2.default.lock(lockPath,{stale:LOCK_TIMEOUT_MS,retries:{retries:5,minTimeout:10,maxTimeout:500,factor:2},realpath:!1})}catch(err){let code=err.code;if(code==="ELOCKED"||code==="EEXIST")return{acquired:!1};throw err}return{acquired:!0,lock:{filePath,agent,taskId,timestamp:new Date().toISOString(),expiresAt:Date.now()+LOCK_TIMEOUT_MS,_release:release}}}function isLocked(directory,filePath){let plLockDir=`${getLockFilePath(directory,filePath)}.lock`;if(fs6.existsSync(plLockDir)){let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}return{filePath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt:acquiredAt+LOCK_TIMEOUT_MS}}return null}function listActiveLocks(directory){let locksDir=path12.join(directory,LOCKS_DIR),locks=[];if(!fs6.existsSync(locksDir))return locks;let files=fs6.readdirSync(locksDir),now=Date.now();for(let file2 of files){if(!file2.endsWith(".lock"))continue;let lockPath=path12.join(locksDir,file2);try{if(fs6.statSync(lockPath).isFile()){let plLockDir=`${lockPath}.lock`;if(fs6.existsSync(plLockDir)){let metaPath=getMetaPath(lockPath),meta3=readMetaFile(metaPath);if(meta3){if(meta3.expiresAt<now)continue;locks.push({filePath:meta3.originalPath,agent:meta3.agent,taskId:meta3.taskId,timestamp:meta3.acquiredAt,expiresAt:meta3.expiresAt,laneId:meta3.laneId})}else{let acquiredAt=Date.now();try{acquiredAt=fs6.statSync(plLockDir).mtimeMs}catch{}let expiresAt=acquiredAt+LOCK_TIMEOUT_MS;if(expiresAt<now)continue;locks.push({filePath:lockPath,agent:"unknown",taskId:"unknown",timestamp:new Date(acquiredAt).toISOString(),expiresAt})}}}}catch{}}return locks}async function acquireLaneLocks(directory,laneId,files,agent,taskId,sessionID){let acquiredLocks=[],conflicts=[];for(let file2 of files){let result=await tryAcquireLock(directory,file2,agent,taskId);if(!result.acquired){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lockPath2=getLockFilePath(directory,lock.filePath),metaPath2=getMetaPath(lockPath2);try{fs6.unlinkSync(metaPath2)}catch{}try{fs6.unlinkSync(lockPath2)}catch{}}catch{}return conflicts.push(file2),{acquired:!1,conflicts}}let lockPath=getLockFilePath(directory,file2),metaPath=getMetaPath(lockPath),meta3={originalPath:file2,laneId,taskId,agent,sessionID,acquiredAt:result.lock.timestamp,expiresAt:result.lock.expiresAt};try{await writeMetaFile(metaPath,meta3)}catch(err){for(let lock of acquiredLocks)try{if(lock._release)await lock._release();let lp=getLockFilePath(directory,lock.filePath),mp=getMetaPath(lp);try{fs6.unlinkSync(mp)}catch{}try{fs6.unlinkSync(lp)}catch{}}catch{}if(result.lock._release)await result.lock._release();try{fs6.unlinkSync(lockPath)}catch{}throw err}result.lock.laneId=laneId,acquiredLocks.push(result.lock)}return{acquired:!0,locks:acquiredLocks}}async function releaseLaneLocks(directory,laneId){let locksDir=path12.join(directory,LOCKS_DIR);if(!fs6.existsSync(locksDir))return 0;let files=fs6.readdirSync(locksDir),releasedCount=0;for(let file2 of files){if(!file2.endsWith(".meta"))continue;let metaPath=path12.join(locksDir,file2),meta3=readMetaFile(metaPath);if(!meta3||meta3.laneId!==laneId)continue;let lockPath=metaPath.replace(/\.meta$/,".lock");try{try{await import_proper_lockfile2.default.unlock(lockPath,{realpath:!1})}catch{}try{fs6.unlinkSync(lockPath)}catch{}try{fs6.unlinkSync(metaPath)}catch{}releasedCount++}catch{}}return releasedCount}var import_proper_lockfile2,LOCKS_DIR=".swarm/locks",LOCK_TIMEOUT_MS=300000,_internals14;var init_file_locks=__esm(()=>{import_proper_lockfile2=__toESM(require_proper_lockfile(),1),_internals14={tryAcquireLock,writeFile:fs6.promises.writeFile}});function defineEntry(kind,input){let entry={kind,category:input.category,severity:input.severity,privacyClass:input.privacyClass,producer:input.producer,consumers:input.consumers,retentionOwnerIssue:input.retentionOwnerIssue,requiredWorkflowIds:input.requiredWorkflowIds??NO_WORKFLOW_IDS,forbiddenWorkflowIds:input.forbiddenWorkflowIds??NO_WORKFLOW_IDS,requiresParent:input.requiresParent??!1,allowsLinks:input.allowsLinks??!0,otelMapping:input.otelMapping??"none",docAnchor:`#${kind}`,testFile:"tests/unit/observability/catalog-contract.test.ts"};if(input.futureOwnerIssue!==void 0)return Object.freeze({...entry,futureOwnerIssue:input.futureOwnerIssue});return Object.freeze(entry)}function getCatalogEntry(kind){return Object.hasOwn(EVENT_CATALOG,kind)?EVENT_CATALOG[kind]:void 0}var NO_WORKFLOW_IDS,NO_CONSUMERS,REQUIRE_SESSION,REQUIRE_SESSION_AND_TASK,REQUIRE_TASK,REQUIRE_COUNCIL_ROUND,FORBID_SESSION,FORBID_COUNCIL_ROUND,CONSUMER_COST_ACCOUNTING,CONSUMER_COST_CORRECTION,CONSUMER_COST_JOIN,CONSUMER_GATE_STATS,CONSUMER_HEARTBEAT_LISTENER,CATALOG_SOURCE,catalog,EVENT_CATALOG,CATALOG_KINDS;var init_catalog=__esm(()=>{NO_WORKFLOW_IDS=Object.freeze([]),NO_CONSUMERS=Object.freeze([]),REQUIRE_SESSION=Object.freeze(["hostSessionId"]),REQUIRE_SESSION_AND_TASK=Object.freeze(["hostSessionId","taskId"]),REQUIRE_TASK=Object.freeze(["taskId"]),REQUIRE_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),FORBID_SESSION=Object.freeze(["hostSessionId"]),FORBID_COUNCIL_ROUND=Object.freeze(["councilRoundId"]),CONSUMER_COST_ACCOUNTING=Object.freeze(["src/services/cost-accounting.ts:431"]),CONSUMER_COST_CORRECTION=Object.freeze(["src/services/cost-accounting.ts:428"]),CONSUMER_COST_JOIN=Object.freeze(["src/services/cost-accounting.ts:415"]),CONSUMER_GATE_STATS=Object.freeze(["src/evaluation/gate-stats.ts:99"]),CONSUMER_HEARTBEAT_LISTENER=Object.freeze(["src/telemetry.ts:268"]);CATALOG_SOURCE=[["session_started",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:654",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["session_ended",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:658",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["agent_activated",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:662",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["task_state_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:700",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"openinference"}],["phase_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:748",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"openinference"}],["heartbeat",{category:"lifecycle",severity:"debug",privacyClass:"pseudonymous",producer:"src/telemetry.ts:930",consumers:CONSUMER_HEARTBEAT_LISTENER,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["turbo_mode_changed",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:938",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["environment_detected",{category:"lifecycle",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:963",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,allowsLinks:!1}],["delegation_begin",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:666",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_end",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:676",consumers:CONSUMER_COST_ACCOUNTING,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_correction",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:786",consumers:CONSUMER_COST_CORRECTION,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK,otelMapping:"genai"}],["delegation_cost_binding",{category:"delegation",severity:"info",privacyClass:"pseudonymous",producer:"src/index.ts:1803",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["delegation_cost_join",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/index.ts:1823",consumers:CONSUMER_COST_JOIN,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"none"}],["model_fallback",{category:"delegation",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:781",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["model_unresolved",{category:"delegation",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:795",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION,otelMapping:"genai"}],["gate_passed",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:709",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_failed",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:726",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["gate_parse_error",{category:"gate",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:713",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["reviewer_gate_decision",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:736",consumers:CONSUMER_GATE_STATS,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION_AND_TASK}],["council_attempt",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:85",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_round_transition",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:115",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,requiredWorkflowIds:REQUIRE_COUNCIL_ROUND}],["council_attempt_unscoped",{category:"gate",severity:"warning",privacyClass:"pseudonymous",producer:"src/council/council-observability.ts:152",consumers:NO_CONSUMERS,futureOwnerIssue:2048,retentionOwnerIssue:2046,forbiddenWorkflowIds:FORBID_COUNCIL_ROUND}],["context_source_attribution",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/services/context-attribution.ts:124",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:REQUIRE_SESSION}],["verdict_row_pipe_recovery",{category:"gate",severity:"info",privacyClass:"pseudonymous",producer:"src/pr-review/legacy-transcript-adapter.ts:691",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045}],["training_vault_health",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1107",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS}],["budget_updated",{category:"cost",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:752",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2043,requiredWorkflowIds:REQUIRE_SESSION}],["context_pruned",{category:"guardrail",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:771",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["retrieval_routed",{category:"guardrail",severity:"info",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1340",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["hard_limit_hit",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:809",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["revision_limit_hit",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:818",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["loop_detected",{category:"guardrail",severity:"warning",privacyClass:"sensitive",producer:"src/telemetry.ts:822",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["scope_violation",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:918",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["qa_skip_violation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:926",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["auto_oversight_escalation",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:948",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["no_op_strong_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:836",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["gate_denial_loop",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:857",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_warning",{category:"guardrail",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:871",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["execution_stall_denied",{category:"guardrail",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:888",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["swarm_internals_read_denied",{category:"guardrail",severity:"error",privacyClass:"sensitive",producer:"src/telemetry.ts:905",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop_delivered",{category:"prm",severity:"error",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1321",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_pattern_detected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:978",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_course_correction_injected",{category:"prm",severity:"notice",privacyClass:"pseudonymous",producer:"src/telemetry.ts:992",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_escalation_triggered",{category:"prm",severity:"warning",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1005",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["prm_hard_stop",{category:"prm",severity:"critical",privacyClass:"pseudonymous",producer:"src/telemetry.ts:1019",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:REQUIRE_SESSION}],["evidence_lock_acquired",{category:"evidence",severity:"info",privacyClass:"sensitive",producer:"src/evidence/lock.ts:99",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_contended",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:134",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["evidence_lock_stale_recovered",{category:"evidence",severity:"notice",privacyClass:"sensitive",producer:"src/evidence/lock.ts:91",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,requiredWorkflowIds:REQUIRE_TASK,forbiddenWorkflowIds:FORBID_SESSION}],["plan_ledger_cas_retry",{category:"plan",severity:"notice",privacyClass:"operational",producer:"src/plan/manager.ts:348",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["plan_md_write_failed",{category:"plan",severity:"warning",privacyClass:"sensitive",producer:"src/plan/manager.ts:1783",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["snapshot_failed",{category:"plan",severity:"error",privacyClass:"sensitive",producer:"src/plan/ledger.ts:1587",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2036,forbiddenWorkflowIds:FORBID_SESSION}],["agent_conflict_detected",{category:"conflict",severity:"warning",privacyClass:"pseudonymous",producer:"src/hooks/conflict-resolution.ts:73",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:Object.freeze(["hostSessionId","phaseId"])}],["close_archive_result",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1056",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047}],["knowledge_receipt_transition",{category:"knowledge",severity:"info",privacyClass:"pseudonymous",producer:"src/hooks/knowledge-receipt-observability.ts:197",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["knowledge_maintenance",{category:"knowledge",severity:"notice",privacyClass:"pseudonymous",producer:"src/knowledge/hive-quarantine.ts:1265",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2045,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["residue_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1078",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["context_telemetry_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1122",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["skill_usage_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1159",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["core_events_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1185",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["shell_audit_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1209",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["trajectory_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1232",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["pr_subscription_health",{category:"lifecycle",severity:"notice",privacyClass:"operational",producer:"src/telemetry.ts:1261",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2047,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}],["learning_health_alarm",{category:"lifecycle",severity:"warning",privacyClass:"operational",producer:"src/telemetry.ts:1305",consumers:NO_CONSUMERS,futureOwnerIssue:2047,retentionOwnerIssue:2044,requiredWorkflowIds:NO_WORKFLOW_IDS,allowsLinks:!1}]],catalog={};for(let[kind,input]of CATALOG_SOURCE)catalog[kind]=defineEntry(kind,input);EVENT_CATALOG=Object.freeze(catalog),CATALOG_KINDS=Object.freeze(Object.keys(EVENT_CATALOG))});var OBSERVABILITY_SCHEMA_VERSION=1,EventCategorySchema,EventSeveritySchema,PrivacyClassSchema,TimingConfidenceSchema,SpanLinkSchema,TraceContextSchema,WorkflowIdsSchema,LineageSchema,ProvenanceSchema,OutcomeSchema,PolicySchema,LegacyProjectionSchema,ObservabilityEventSchema;var init_envelope=__esm(()=>{init_zod();EventCategorySchema=exports_external.enum(["lifecycle","delegation","gate","plan","evidence","guardrail","knowledge","cost","prm","conflict","unrecognized"]),EventSeveritySchema=exports_external.enum(["debug","info","notice","warning","error","critical"]),PrivacyClassSchema=exports_external.enum(["operational","pseudonymous","sensitive","content"]),TimingConfidenceSchema=exports_external.enum(["exact","writer-clock","inferred","unknown"]),SpanLinkSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),kind:exports_external.enum(["resume","lane","cross-process","retry","parent-batch"]),note:exports_external.string().optional()}),TraceContextSchema=exports_external.object({traceId:exports_external.string(),spanId:exports_external.string(),parentSpanId:exports_external.string().optional(),links:exports_external.array(SpanLinkSchema)}),WorkflowIdsSchema=exports_external.object({rootConversationId:exports_external.string().optional(),hostSessionId:exports_external.string().optional(),swarmSessionId:exports_external.string().optional(),taskId:exports_external.string().optional(),phaseId:exports_external.string().optional(),laneId:exports_external.string().optional(),batchId:exports_external.string().optional(),resultId:exports_external.string().optional(),councilRoundId:exports_external.string().optional(),backgroundInvocationId:exports_external.string().optional(),knowledgeTraceId:exports_external.string().optional(),knowledgeEntryId:exports_external.string().optional(),prRunId:exports_external.string().optional()}),LineageSchema=exports_external.object({projectRef:exports_external.string().optional(),cohortRef:exports_external.string().optional(),worktreeRef:exports_external.string().optional()}),ProvenanceSchema=exports_external.object({pluginVersion:exports_external.string().optional(),opencodeVersion:exports_external.string().optional(),runtime:exports_external.string().optional(),runtimeVersion:exports_external.string().optional(),os:exports_external.string().optional(),arch:exports_external.string().optional(),model:exports_external.string().optional(),provider:exports_external.string().optional(),gitSha:exports_external.string().optional(),configHash:exports_external.string().optional()}),OutcomeSchema=exports_external.object({status:exports_external.enum(["success","failure","partial","unknown"]).optional(),reason:exports_external.string().optional(),errorName:exports_external.string().optional(),errorMessage:exports_external.string().optional(),retryIndex:exports_external.number().optional(),durationMs:exports_external.number().optional()}),PolicySchema=exports_external.object({sampled:exports_external.boolean(),sampleRate:exports_external.number(),dropReason:exports_external.string().optional(),privacyClass:PrivacyClassSchema}),LegacyProjectionSchema=exports_external.object({sourceStore:exports_external.string(),sourceSchemaVersion:exports_external.number().nullable(),timingConfidence:TimingConfidenceSchema,unknown:exports_external.array(exports_external.string()),extra:exports_external.record(exports_external.string(),exports_external.unknown()),raw:exports_external.unknown()}),ObservabilityEventSchema=exports_external.object({schemaVersion:exports_external.number(),eventId:exports_external.string(),kind:exports_external.string(),category:EventCategorySchema,severity:EventSeveritySchema,occurredAt:exports_external.string(),observedAt:exports_external.string(),writerSequence:exports_external.number(),trace:TraceContextSchema,workflow:WorkflowIdsSchema,lineage:LineageSchema,provenance:ProvenanceSchema,outcome:OutcomeSchema,policy:PolicySchema,legacy:LegacyProjectionSchema,relationshipViolations:exports_external.array(exports_external.string())})});import{createHash as createHash7,randomBytes as randomBytes2,randomUUID as randomUUID2}from"node:crypto";function newTraceId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(TRACE_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_TRACE_ID)return hex3}return SENTINEL_TRACE_ID}function newSpanId(){for(let attempt=0;attempt<MAX_REGENERATION_ATTEMPTS;attempt++){let hex3=randomBytes2(SPAN_ID_BYTES).toString("hex");if(hex3!==ALL_ZERO_SPAN_ID)return hex3}return SENTINEL_SPAN_ID}function newEventId(){return randomUUID2()}function takeIdBytes(){let need=TRACE_ID_BYTES+SPAN_ID_BYTES;if(_poolOffset+need>_pool.length)_pool=randomBytes2(POOL_BYTES),_poolOffset=0;let slice=_pool.subarray(_poolOffset,_poolOffset+need);return _poolOffset+=need,slice}function newTraceAndSpanId(){let buffer=takeIdBytes(),traceId=buffer.subarray(0,TRACE_ID_BYTES).toString("hex"),spanId=buffer.subarray(TRACE_ID_BYTES).toString("hex");if(traceId===ALL_ZERO_TRACE_ID||spanId===ALL_ZERO_SPAN_ID)return{traceId:newTraceId(),spanId:newSpanId()};return{traceId,spanId}}function resolveLineageSalt(){let configured=process.env[LINEAGE_SALT_ENV];if(typeof configured==="string"&&configured.length>0)return configured;return DEFAULT_LINEAGE_SALT}function pseudonymousRef(absolutePath,salt){return createHash7("sha256").update(salt+LINEAGE_SEPARATOR+absolutePath,"utf8").digest("hex").slice(0,PSEUDONYMOUS_REF_LENGTH)}function pseudonymousSessionRef(sessionId,salt=resolveLineageSalt()){return pseudonymousRef(sessionId,salt)}var TRACE_ID_BYTES=16,SPAN_ID_BYTES=8,TRACE_ID_HEX_LENGTH,SPAN_ID_HEX_LENGTH,ALL_ZERO_TRACE_ID,ALL_ZERO_SPAN_ID,SENTINEL_TRACE_ID,SENTINEL_SPAN_ID,MAX_REGENERATION_ATTEMPTS=4,LINEAGE_SALT_ENV="SWARM_OBSERVABILITY_LINEAGE_SALT",DEFAULT_LINEAGE_SALT="opencode-swarm/observability/lineage/v1",LINEAGE_SEPARATOR="\x00",PSEUDONYMOUS_REF_LENGTH=16,POOL_DRAWS=128,POOL_BYTES,_pool,_poolOffset;var init_ids=__esm(()=>{TRACE_ID_HEX_LENGTH=TRACE_ID_BYTES*2,SPAN_ID_HEX_LENGTH=SPAN_ID_BYTES*2,ALL_ZERO_TRACE_ID="0".repeat(TRACE_ID_HEX_LENGTH),ALL_ZERO_SPAN_ID="0".repeat(SPAN_ID_HEX_LENGTH),SENTINEL_TRACE_ID=`${"0".repeat(TRACE_ID_HEX_LENGTH-1)}1`,SENTINEL_SPAN_ID=`${"0".repeat(SPAN_ID_HEX_LENGTH-1)}1`;POOL_BYTES=(TRACE_ID_BYTES+SPAN_ID_BYTES)*POOL_DRAWS,_pool=Buffer.alloc(0),_poolOffset=Number.POSITIVE_INFINITY});function degradedProjection(marker,data){return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:[marker],extra:EMPTY_EXTRA,raw:data}}function knownKeySetFor(knownKeys){let cached2=_knownKeySetCache.get(knownKeys);if(cached2!==void 0)return cached2;let built=new Set(knownKeys);return _knownKeySetCache.set(knownKeys,built),built}function adaptLegacyTelemetryPayload(kind,data,knownKeys){if(data===null||typeof data!=="object")return degradedProjection("<non-object-payload>",data);try{let record2=data,known=knownKeySetFor(knownKeys),ownKeys=Object.keys(record2),extra;for(let key of ownKeys){if(known.has(key))continue;if(extra??={},key==="__proto__"){Object.defineProperty(extra,key,{value:record2[key],enumerable:!0,writable:!0,configurable:!0});continue}extra[key]=record2[key]}let unknownFields;for(let key of knownKeys)if(record2[key]===void 0)unknownFields??=[],unknownFields.push(key);return{sourceStore:".swarm/telemetry.jsonl",sourceSchemaVersion:null,timingConfidence:"writer-clock",unknown:unknownFields??EMPTY_UNKNOWN,extra:extra??EMPTY_EXTRA,raw:data}}catch{return degradedProjection("<payload-introspection-failed>",data)}}function nonEmptyString(value){return typeof value==="string"&&value.length>0?value:void 0}function extractWorkflowIds(data){let ids={};try{if(data===null||typeof data!=="object")return ids;let record2=data,hostSessionId=nonEmptyString(record2.sessionId);if(hostSessionId!==void 0)ids.hostSessionId=hostSessionId;let taskId=nonEmptyString(record2.taskId);if(taskId!==void 0)ids.taskId=taskId;let laneId=nonEmptyString(record2.laneId);if(laneId!==void 0)ids.laneId=laneId;let batchId=nonEmptyString(record2.batchId);if(batchId!==void 0)ids.batchId=batchId;let councilRoundId=nonEmptyString(record2.councilRoundId);if(councilRoundId!==void 0)ids.councilRoundId=councilRoundId;let knowledgeTraceId=nonEmptyString(record2.knowledgeTraceId);if(knowledgeTraceId!==void 0)ids.knowledgeTraceId=knowledgeTraceId;let knowledgeEntryId=nonEmptyString(record2.knowledgeEntryId);if(knowledgeEntryId!==void 0)ids.knowledgeEntryId=knowledgeEntryId;let phase=record2.phase;if(typeof phase==="number"&&Number.isFinite(phase))ids.phaseId=String(phase);else{let phaseString=nonEmptyString(phase);if(phaseString!==void 0)ids.phaseId=phaseString}}catch{}return ids}function extractOutcome(data){let outcome={};try{if(data===null||typeof data!=="object")return outcome;let record2=data,result=nonEmptyString(record2.result);if(result!==void 0){let normalized=result.toLowerCase();outcome.status=Object.hasOwn(RESULT_STATUS_MAP,normalized)?RESULT_STATUS_MAP[normalized]:"unknown"}let reason=nonEmptyString(record2.reason);if(reason!==void 0)outcome.reason=reason;let errorName=nonEmptyString(record2.errorName);if(errorName!==void 0)outcome.errorName=errorName;let errorMessage=nonEmptyString(record2.errorMessage);if(errorMessage!==void 0)outcome.errorMessage=errorMessage;let retryIndex=record2.retry_index;if(typeof retryIndex==="number"&&Number.isFinite(retryIndex))outcome.retryIndex=retryIndex}catch{}return outcome}var LEGACY_TELEMETRY_SOURCE_STORE=".swarm/telemetry.jsonl",LEGACY_ADAPTER_RULES,KNOWN_TELEMETRY_KEYS,EMPTY_EXTRA,EMPTY_UNKNOWN,_knownKeySetCache,RESULT_STATUS_MAP;var init_legacy=__esm(()=>{LEGACY_ADAPTER_RULES=Object.freeze(["Preserve unknown fields: an own key the contract does not recognize is kept under `extra` by reference and is never dropped.","Record the source store and its schema version: `sourceStore` names the file; `sourceSchemaVersion` is the version the store declares.","Preserve originally reported values: values are aliased, never coerced, normalized, rounded, or re-serialized.","Record timing confidence: a time read by the writer at record time is `writer-clock`, never `exact`.","Unknown is not zero: the adapter lists in `unknown` every catalogued key the PRODUCER left undefined, and never itself defaults one to 0, \"\", false, or null. The guarantee stops at the adapter boundary — a producer that pre-coerces its own defaults defeats it, because the adapter only ever sees the coerced value. The known instance is `delegation_end` (`src/telemetry.ts` `delegationEnd`, pre-existing): it coerces `?? 0` / `?? null` / `?? 'unavailable'` before emitting, so its cost fields can never appear in `unknown`; there, `cost_source: 'unavailable'` is how absence stays recoverable.","Missing lineage stays missing: an absent correlation ID stays `undefined` and is never synthesized to make a join succeed.","Never drop unrecognized fields: no allowlist filter is applied to the payload on the way through."]),KNOWN_TELEMETRY_KEYS=Object.freeze({session_started:Object.freeze(["sessionId","agentName"]),session_ended:Object.freeze(["sessionId","reason"]),agent_activated:Object.freeze(["sessionId","agentName","oldName"]),delegation_begin:Object.freeze(["sessionId","agentName","taskId"]),delegation_end:Object.freeze(["sessionId","agentName","taskId","result","tokens_input","tokens_output","tokens_reasoning","tokens_cache","cost_usd","cost_source","model","gate","retry_index","cost_evidence","evidence_status","evidence_reason","currency","record_id","identity_fingerprint","parent_session_digest","child_session_digest","version"]),delegation_cost_correction:Object.freeze(["sessionId","agentName","taskId","parent_session_digest","record_id","identity_fingerprint","version","cost_evidence","evidence_status","evidence_reason","currency","cost_usd","cost_source","tokens_input","tokens_output","tokens_reasoning","tokens_cache","model","gate","retry_index"]),delegation_cost_binding:Object.freeze(["sessionId","record_id","identity_fingerprint","child_session_digest"]),delegation_cost_join:Object.freeze(["sessionId","reason"]),task_state_changed:Object.freeze(["sessionId","taskId","newState","oldState"]),gate_passed:Object.freeze(["sessionId","gate","taskId"]),gate_parse_error:Object.freeze(["taskId","errorName","errorMessage"]),gate_failed:Object.freeze(["sessionId","gate","taskId","reason"]),reviewer_gate_decision:Object.freeze(["sessionId","gate","taskId","blocked","allowed","reasonCode","evidenceKind"]),phase_changed:Object.freeze(["sessionId","oldPhase","newPhase"]),budget_updated:Object.freeze(["sessionId","budgetPct","agentName"]),context_pruned:Object.freeze(["sessionId","agentName","trigger","usageSource","beforeTokens","afterTokens","modelLimit","maskedMessages","maskedToolParts","maskedTokensFreed","prunedMessages","prunedTextParts","prunedToolParts","prunedTokensFreed"]),model_fallback:Object.freeze(["sessionId","agentName","fromModel","toModel","reason"]),model_unresolved:Object.freeze(["sessionId","agentName","model","detail"]),hard_limit_hit:Object.freeze(["sessionId","agentName","limitType","value"]),revision_limit_hit:Object.freeze(["sessionId","agentName"]),loop_detected:Object.freeze(["sessionId","agentName","loopType"]),scope_violation:Object.freeze(["sessionId","agentName","file","reason"]),qa_skip_violation:Object.freeze(["sessionId","agentName","skipCount"]),heartbeat:Object.freeze(["sessionId"]),turbo_mode_changed:Object.freeze(["sessionId","enabled","agentName"]),auto_oversight_escalation:Object.freeze(["sessionId","reason","interactionCount","deadlockCount","phase"]),environment_detected:Object.freeze(["sessionId","hostOS","shellFamily","executionMode"]),prm_pattern_detected:Object.freeze(["sessionId","pattern","severity","category","stepRange"]),prm_course_correction_injected:Object.freeze(["sessionId","pattern","level"]),prm_escalation_triggered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),prm_hard_stop:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),no_op_strong_warning:Object.freeze(["sessionId","agentName","count","threshold"]),gate_denial_loop:Object.freeze(["sessionId","tool","code","count"]),execution_stall_warning:Object.freeze(["sessionId","count","threshold"]),execution_stall_denied:Object.freeze(["sessionId","tool","count","threshold"]),swarm_internals_read_denied:Object.freeze(["sessionId","tool","target"]),prm_hard_stop_delivered:Object.freeze(["sessionId","pattern","level","occurrenceCount"]),evidence_lock_acquired:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_contended:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),evidence_lock_stale_recovered:Object.freeze(["directory","evidencePath","agent","taskId","attempt"]),plan_ledger_cas_retry:Object.freeze(["attempt","expectedHashPrefix","delayMs"]),plan_md_write_failed:Object.freeze(["directory","error","timestamp"]),snapshot_failed:Object.freeze(["error","retries","source"]),agent_conflict_detected:Object.freeze(["type","timestamp","sessionId","phase","taskId","sourceAgent","targetAgent","conflictType","resolutionPath","summary"]),knowledge_receipt_transition:Object.freeze(["transition","reasonCode","schemaVersion","receiptSemantics","knowledgeTraceId","knowledgeEntryId","sessionId","taskId","phase","receiptOutcome","receiptSource"]),knowledge_maintenance:Object.freeze(["phase","abortReason","selectedCount","storeEntriesBefore","storeEntriesAfter","backupBytes","storeSha256Prefix","token12"]),residue_health:Object.freeze(["trigger","scanned","matched","eligible","ambiguous","quarantined","preserved","total_bytes","oldest_age_ms","grammar_counts"]),training_vault_health:Object.freeze(["project_ref","reason","count"]),context_telemetry_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),skill_usage_health:Object.freeze(["trigger","accepted","compacted","dropped","skills_dropped","corrupt","pending_retained","uncertain_retained","uncertain_expired","pending_evicted","no_source_knowledge","no_matching_knowledge","bump_retry","bump_unrecoverable","bump_applied_zero","pressure","curator_skipped","bytes","limit_bytes","oldest_timestamp","newest_timestamp","coverage"]),learning_health_alarm:Object.freeze(["alarm","transition","severity","scope_class","session_ref","model","provider","window_ms","coverage_facts","raise_facts","age_ms","limit_source","denominator_fallback","pressure_pct","band","share_pct","field_count","non_field_count","store","dropped","corrupt","retained","accepted","gap_type","role","phase","reason"]),core_events_health:Object.freeze(["trigger","accepted_count","compacted_count","retained_count","dropped_count","corrupt_count","authority_index_count","authority_evicted_count","oldest_timestamp","newest_timestamp","bytes","limit_bytes"]),council_attempt:Object.freeze(["sessionId","councilRoundId","level","stage","attemptId","disposition","taskId","phase","identityDigest","authoritativeRound","clientRound","verdictCount","memberCount","quorumSize","verdict","transition","gateEffect"]),council_round_transition:Object.freeze(["sessionId","councilRoundId","level","attemptId","transition","gateEffect","taskId","phase","identityDigest","round","nextRound","roundStatus","maxRoundsExhausted","verdict","quorumSize"]),council_attempt_unscoped:Object.freeze(["sessionId","level","disposition","fingerprint","attemptId"])}),EMPTY_EXTRA=Object.freeze({});EMPTY_UNKNOWN=Object.freeze([]),_knownKeySetCache=new WeakMap;RESULT_STATUS_MAP=Object.freeze({success:"success",succeeded:"success",ok:"success",pass:"success",passed:"success",complete:"success",completed:"success",failure:"failure",failed:"failure",fail:"failure",error:"failure",partial:"partial"})});function validateEventRelationships(event){let violations=[];try{let entry=getCatalogEntry(event.kind),links=Array.isArray(event.trace?.links)?event.trace.links:[];if(entry===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.unknownKind}:${event.kind}`);else{let workflow=event.workflow??{};for(let id of entry.requiredWorkflowIds)if(workflow[id]===void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.requiredWorkflowIdMissing}:${id}`);for(let id of entry.forbiddenWorkflowIds)if(workflow[id]!==void 0)violations.push(`${RELATIONSHIP_VIOLATION_CODES.forbiddenWorkflowIdPresent}:${id}`);let parentSpanId=event.trace?.parentSpanId;if(!entry.requiresParent&&parentSpanId!==void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanNotAllowed);if(entry.requiresParent&&parentSpanId===void 0)violations.push(RELATIONSHIP_VIOLATION_CODES.parentSpanMissing);if(parentSpanId!==void 0&&!SPAN_ID_PATTERN.test(String(parentSpanId)))violations.push(RELATIONSHIP_VIOLATION_CODES.malformedParentSpanId);if(!entry.allowsLinks&&links.length>0)violations.push(RELATIONSHIP_VIOLATION_CODES.linksNotAllowed)}for(let index=0;index<links.length;index++){let link=links[index];if(link===void 0||link===null)continue;if(!TRACE_ID_PATTERN.test(String(link.traceId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkTraceId}:${index}`);if(!SPAN_ID_PATTERN.test(String(link.spanId)))violations.push(`${RELATIONSHIP_VIOLATION_CODES.malformedLinkSpanId}:${index}`)}}catch{return{ok:!1,violations:[RELATIONSHIP_VIOLATION_CODES.validationFailed]}}return violations.length===0?{ok:!0}:{ok:!1,violations}}var TRACE_ID_PATTERN,SPAN_ID_PATTERN,RELATIONSHIP_VIOLATION_CODES;var init_relationships=__esm(()=>{init_catalog();TRACE_ID_PATTERN=/^[0-9a-f]{32}$/,SPAN_ID_PATTERN=/^[0-9a-f]{16}$/,RELATIONSHIP_VIOLATION_CODES=Object.freeze({unknownKind:"unknown_kind",requiredWorkflowIdMissing:"required_workflow_id_missing",forbiddenWorkflowIdPresent:"forbidden_workflow_id_present",parentSpanNotAllowed:"parent_span_not_allowed",parentSpanMissing:"parent_span_missing",malformedParentSpanId:"malformed_parent_span_id",linksNotAllowed:"links_not_allowed",malformedLinkTraceId:"malformed_link_trace_id",malformedLinkSpanId:"malformed_link_span_id",validationFailed:"relationship_validation_failed"})});function shouldSample(traceId,rate){if(typeof rate!=="number"||!Number.isFinite(rate))return!0;if(rate>=1)return!0;if(rate<=0)return!1;if(typeof traceId!=="string"||traceId.length<8)return!0;let suffix=traceId.slice(-8).toLowerCase();if(!SAMPLE_SUFFIX_PATTERN.test(suffix))return!0;let value=Number.parseInt(suffix,16);if(!Number.isFinite(value))return!0;return value/4294967295<rate}var DEFAULT_SAMPLE_RATE=1,SAMPLE_SUFFIX_PATTERN,METRIC_LABEL_ALLOWLIST,ALLOWED_LABELS,CARDINALITY_VIOLATION_CODES;var init_sampling=__esm(()=>{SAMPLE_SUFFIX_PATTERN=/^[0-9a-f]{8}$/;METRIC_LABEL_ALLOWLIST=Object.freeze(["kind","category","severity","outcome_status","cost_source","privacy_class","runtime","os","provider","sampled"]),ALLOWED_LABELS=new Set(METRIC_LABEL_ALLOWLIST),CARDINALITY_VIOLATION_CODES=Object.freeze({notAllowlisted:"label_not_allowlisted",highCardinalityShape:"high_cardinality_label_shape"})});function initObservability(input){try{let salt=resolveLineageSalt(),lineage={},directory=typeof input.directory==="string"&&input.directory.length>0?input.directory:void 0;if(directory!==void 0)lineage.projectRef=pseudonymousRef(directory,salt);if(typeof input.cohortLabel==="string"&&input.cohortLabel.length>0)lineage.cohortRef=pseudonymousRef(`${directory??""}\x00cohort\x00${input.cohortLabel}`,salt);if(typeof input.worktreeId==="string"&&input.worktreeId.length>0)lineage.worktreeRef=pseudonymousRef(`${directory??""}\x00worktree\x00${input.worktreeId}`,salt);if(_lineage=Object.freeze(lineage),_provenance=Object.freeze(input.provenance?{...input.provenance}:{}),typeof input.sampleRate==="number"&&Number.isFinite(input.sampleRate))_sampleRate=input.sampleRate}catch{}}function nextWriterSequence(){if(_writerSequence>=Number.MAX_SAFE_INTEGER)_writerSequence=0;return _writerSequence+=1,_writerSequence}function safeNowIso(){try{return new Date().toISOString()}catch{return FALLBACK_TIMESTAMP}}function buildFallbackObservation(kind,data,writerSequence){let now=safeNowIso();return{schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:FALLBACK_EVENT_ID,kind,category:"unrecognized",severity:"error",occurredAt:now,observedAt:now,writerSequence,trace:{traceId:FALLBACK_TRACE_ID,spanId:FALLBACK_SPAN_ID,links:[]},workflow:{},lineage:{},provenance:{},outcome:{},policy:{sampled:shouldSample(FALLBACK_TRACE_ID,_sampleRate),sampleRate:_sampleRate,privacyClass:"operational"},legacy:{sourceStore:LEGACY_TELEMETRY_SOURCE_STORE,sourceSchemaVersion:null,timingConfidence:"unknown",unknown:[],extra:{},raw:data},relationshipViolations:[OBSERVATION_BUILD_FAILED]}}function createObservation(kind,data){let writerSequence=nextWriterSequence();try{let entry=getCatalogEntry(kind),{traceId,spanId}=newTraceAndSpanId(),observedAt=new Date().toISOString(),knownKeys=Object.hasOwn(KNOWN_TELEMETRY_KEYS,kind)?KNOWN_TELEMETRY_KEYS[kind]:EMPTY_KNOWN_KEYS,event={schemaVersion:OBSERVABILITY_SCHEMA_VERSION,eventId:newEventId(),kind,category:entry?.category??"unrecognized",severity:entry?.severity??"warning",occurredAt:observedAt,observedAt,writerSequence,trace:{traceId,spanId,links:[]},workflow:extractWorkflowIds(data),lineage:_lineage,provenance:_provenance,outcome:extractOutcome(data),policy:{sampled:shouldSample(traceId,_sampleRate),sampleRate:_sampleRate,privacyClass:entry?.privacyClass??"operational"},legacy:adaptLegacyTelemetryPayload(kind,data,knownKeys),relationshipViolations:[]},validation=validateEventRelationships(event);if(!validation.ok)event.relationshipViolations=validation.violations;return event}catch{return buildFallbackObservation(kind,data,writerSequence)}}function toLegacyTelemetryLine(event){return{timestamp:event.observedAt,event:event.kind,...event.legacy.raw}}function canonicalLineContent(event){return JSON.stringify(toLegacyTelemetryLine(event))}var _provenance,_lineage,_writerSequence=0,_sampleRate,EMPTY_KNOWN_KEYS,FALLBACK_EVENT_ID="00000000-0000-4000-8000-000000000000",FALLBACK_TRACE_ID="00000000000000000000000000000001",FALLBACK_SPAN_ID="0000000000000001",FALLBACK_TIMESTAMP="1970-01-01T00:00:00.000Z",OBSERVATION_BUILD_FAILED="observation_build_failed";var init_observe=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_relationships();init_sampling();_provenance=Object.freeze({}),_lineage=Object.freeze({}),_sampleRate=DEFAULT_SAMPLE_RATE,EMPTY_KNOWN_KEYS=Object.freeze([])});var OTEL_GENAI_MAPPING_VERSION="1.29.0",OPENINFERENCE_MAPPING_VERSION="0.1.14",OTEL_GENAI_ATTRIBUTES,OPENINFERENCE_ATTRIBUTES,NO_ATTRIBUTES;var init_otel_mapping=__esm(()=>{OTEL_GENAI_ATTRIBUTES=Object.freeze({kind:"gen_ai.operation.name","provenance.provider":"gen_ai.system","provenance.model":"gen_ai.request.model","legacy.raw.model":"gen_ai.response.model","legacy.raw.agentName":"gen_ai.agent.name","workflow.hostSessionId":"gen_ai.conversation.id","outcome.status":"gen_ai.response.finish_reasons","legacy.raw.tokens_input":"gen_ai.usage.input_tokens","legacy.raw.tokens_output":"gen_ai.usage.output_tokens","legacy.raw.tokens_cache":"gen_ai.usage.cache_read_input_tokens","legacy.raw.tokens_reasoning":"swarm.gen_ai.usage.reasoning_tokens","legacy.raw.cost_usd":"swarm.gen_ai.usage.cost_usd"}),OPENINFERENCE_ATTRIBUTES=Object.freeze({kind:"openinference.span.kind","provenance.model":"llm.model_name","provenance.provider":"llm.provider","legacy.raw.agentName":"agent.name","workflow.hostSessionId":"session.id","legacy.raw.tokens_input":"llm.token_count.prompt","legacy.raw.tokens_output":"llm.token_count.completion","legacy.raw.tokens_cache":"llm.token_count.prompt_details.cache_read","legacy.raw.tokens_reasoning":"llm.token_count.completion_details.reasoning","legacy.raw.cost_usd":"swarm.llm.cost_usd"}),NO_ATTRIBUTES=Object.freeze({})});var init_observability=__esm(()=>{init_catalog();init_envelope();init_ids();init_legacy();init_observe();init_otel_mapping();init_relationships();init_sampling()});var exports_telemetry={};__export(exports_telemetry,{telemetry:()=>telemetry,stopHeartbeatTracking:()=>stopHeartbeatTracking,startHeartbeatTracking:()=>startHeartbeatTracking,rotateTelemetryIfNeeded:()=>rotateTelemetryIfNeeded,resetTelemetryForTesting:()=>resetTelemetryForTesting,resetHeartbeatTrackingForTesting:()=>resetHeartbeatTrackingForTesting,removeTelemetryListener:()=>removeTelemetryListener,initTelemetry:()=>initTelemetry,getLastHeartbeat:()=>getLastHeartbeat,flushAndDrainTelemetry:()=>flushAndDrainTelemetry,emit:()=>emit,addTelemetryListener:()=>addTelemetryListener,_internals:()=>_internals15,ROTATION_CHECK_INTERVAL:()=>ROTATION_CHECK_INTERVAL});import*as fs7 from"node:fs";import{createWriteStream}from"node:fs";import*as os3 from"node:os";import*as path13 from"node:path";function capHeartbeatMap(){while(heartbeatTimestamps.size>=500){let oldestKey=heartbeatTimestamps.keys().next().value;if(oldestKey===void 0)break;heartbeatTimestamps.delete(oldestKey)}}function startHeartbeatTracking(){if(_heartbeatTrackingActive)return;_heartbeatTrackingActive=!0;let listener=(event,data)=>{if(event!=="heartbeat")return;let payload=data;if(!payload?.sessionId)return;heartbeatTimestamps.set(payload.sessionId,Date.now()),capHeartbeatMap()};_heartbeatListener=listener,addTelemetryListener(listener)}function getLastHeartbeat(sessionId){return heartbeatTimestamps.get(sessionId)}function stopHeartbeatTracking(){if(_heartbeatTrackingActive=!1,_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetHeartbeatTrackingForTesting(){if(_heartbeatTrackingActive=!1,heartbeatTimestamps.clear(),_heartbeatListener!==null){let idx=_listeners.indexOf(_heartbeatListener);if(idx>=0)_listeners.splice(idx,1);_heartbeatListener=null}}function resetTelemetryForTesting(){if(_disabled=!1,_projectDirectory=null,_listeners.length=0,_emitCount=0,resetHeartbeatTrackingForTesting(),_writeStream!==null)_writeStream.end(),_writeStream=null}function initTelemetry(projectDirectory){if(_disabled)return;if(_writeStream!==null&&_projectDirectory!==null&&sameProjectRoot(_projectDirectory,projectDirectory))return;let oldStream=_writeStream;try{let swarmDir=path13.join(projectDirectory,".swarm");if(!fs7.existsSync(swarmDir))fs7.mkdirSync(swarmDir,{recursive:!0});let telemetryPath=path13.join(swarmDir,"telemetry.jsonl"),stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream,_projectDirectory=projectDirectory}catch(error49){log(`[telemetry] failed to open the new project's telemetry stream (retaining the previous stream, non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`);return}if(oldStream!==null)try{oldStream.end()}catch(error49){log(`[telemetry] failed to close the previous project's stream during re-home (non-fatal): ${error49 instanceof Error?error49.message:String(error49)}`)}}function emit(event,data){try{if(_disabled||_writeStream===null)return;let canonical=_internals15.createObservation(event,data),content=_internals15.canonicalLineContent(canonical),line=content+os3.EOL,stream=_writeStream;stream.write(line,(err)=>{if(err&&_writeStream===stream)_disabled=!0,_writeStream=null});for(let listener of _listeners)try{listener(event,data,canonical,content)}catch{}if(_emitCount++,_emitCount>=ROTATION_CHECK_INTERVAL)_emitCount=0,_internals15.rotateTelemetryIfNeeded()}catch{}}function addTelemetryListener(callback){_listeners.push(callback)}function removeTelemetryListener(callback){let idx=_listeners.indexOf(callback);if(idx>=0)_listeners.splice(idx,1)}function rotateTelemetryIfNeeded(maxBytes=10485760){try{if(_projectDirectory===null)return;let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");if(!fs7.existsSync(telemetryPath))return;if(fs7.statSync(telemetryPath).size<maxBytes)return;let rotatedPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl.1");if(fs7.renameSync(telemetryPath,rotatedPath),_writeStream!==null){_writeStream.end();let stream=createWriteStream(telemetryPath,{flags:"a"});stream.on("error",()=>{if(_writeStream===stream)_disabled=!0,_writeStream=null}),_writeStream=stream}}catch{}}async function flushAndDrainTelemetry(){let stream=_writeStream;if(stream===null||_projectDirectory===null)return;let next;try{let telemetryPath=path13.join(_projectDirectory,".swarm","telemetry.jsonl");next=createWriteStream(telemetryPath,{flags:"a"}),next.on("error",()=>{if(_writeStream===next)_disabled=!0,_writeStream=null}),_writeStream=next}catch{_disabled=!0,_writeStream=null;return}await new Promise((resolve9)=>{stream.end(()=>resolve9())})}var _writeStream=null,_projectDirectory=null,_listeners,_disabled=!1,_heartbeatTrackingActive=!1,_heartbeatListener=null,heartbeatTimestamps,_emitCount=0,ROTATION_CHECK_INTERVAL=50,telemetry,_internals15;var init_telemetry=__esm(()=>{init_observability();init_utils();init_canonical_root();_listeners=[],heartbeatTimestamps=new Map;telemetry={sessionStarted(sessionId,agentName){_internals15.emit("session_started",{sessionId,agentName})},sessionEnded(sessionId,reason){_internals15.emit("session_ended",{sessionId,reason})},agentActivated(sessionId,agentName,oldName){_internals15.emit("agent_activated",{sessionId,agentName,oldName})},delegationBegin(sessionId,agentName,taskId){_internals15.emit("delegation_begin",{sessionId,agentName,taskId})},delegationEnd(sessionId,agentName,taskId,result,costFields){_internals15.emit("delegation_end",{sessionId,agentName,taskId,result,tokens_input:costFields?.tokens_input??0,tokens_output:costFields?.tokens_output??0,tokens_reasoning:costFields?.tokens_reasoning??0,tokens_cache:costFields?.tokens_cache??0,cost_usd:costFields?.cost_usd??null,...costFields,cost_source:costFields?.cost_source??"unavailable",model:costFields?.model,gate:costFields?.gate,retry_index:costFields?.retry_index})},taskStateChanged(sessionId,taskId,newState,oldState){_internals15.emit("task_state_changed",{sessionId,taskId,newState,oldState})},gatePassed(sessionId,gate,taskId){_internals15.emit("gate_passed",{sessionId,gate,taskId})},gateParseError(taskId,error49){_internals15.emit("gate_parse_error",{taskId,errorName:error49.name,errorMessage:error49.message.slice(0,200)})},gateFailed(sessionId,gate,taskId,reason){_internals15.emit("gate_failed",{sessionId,gate,taskId,reason})},reviewerGateDecision(sessionId,taskId,blocked,reasonCode,evidenceKind){_internals15.emit("reviewer_gate_decision",{sessionId,gate:"qa_gate",taskId,blocked,allowed:!blocked,reasonCode,evidenceKind})},phaseChanged(sessionId,oldPhase,newPhase){_internals15.emit("phase_changed",{sessionId,oldPhase,newPhase})},budgetUpdated(sessionId,budgetPct,agentName){_internals15.emit("budget_updated",{sessionId,budgetPct,agentName})},contextPruned(data){_internals15.emit("context_pruned",data)},modelFallback(sessionId,agentName,fromModel,toModel,reason){_internals15.emit("model_fallback",{sessionId,agentName,fromModel,toModel,reason})},modelUnresolved(agentName,model,detail){_internals15.emit("model_unresolved",{sessionId:"preflight",agentName,model,detail})},hardLimitHit(sessionId,agentName,limitType,value){_internals15.emit("hard_limit_hit",{sessionId,agentName,limitType,value})},revisionLimitHit(sessionId,agentName){_internals15.emit("revision_limit_hit",{sessionId,agentName})},loopDetected(sessionId,agentName,loopType){_internals15.emit("loop_detected",{sessionId,agentName,loopType})},noOpStrongWarning(sessionId,agentName,count,threshold){_internals15.emit("no_op_strong_warning",{sessionId,agentName,count,threshold})},gateDenialLoop(sessionId,tool,code,count){_internals15.emit("gate_denial_loop",{sessionId,tool,code,count})},executionStallWarning(sessionId,count,threshold){_internals15.emit("execution_stall_warning",{sessionId,count,threshold})},executionStallDenied(sessionId,tool,count,threshold){_internals15.emit("execution_stall_denied",{sessionId,tool,count,threshold})},swarmInternalsReadDenied(sessionId,tool,target){_internals15.emit("swarm_internals_read_denied",{sessionId,tool,target})},scopeViolation(sessionId,agentName,file2,reason){_internals15.emit("scope_violation",{sessionId,agentName,file:file2,reason})},qaSkipViolation(sessionId,agentName,skipCount){_internals15.emit("qa_skip_violation",{sessionId,agentName,skipCount})},heartbeat(sessionId){_internals15.emit("heartbeat",{sessionId})},turboModeChanged(sessionId,enabled,agentName){_internals15.emit("turbo_mode_changed",{sessionId,enabled,agentName})},autoOversightEscalation(sessionId,reason,interactionCount,deadlockCount,phase){_internals15.emit("auto_oversight_escalation",{sessionId,reason,interactionCount,deadlockCount,phase})},environmentDetected(sessionId,hostOS,shellFamily,executionMode){_internals15.emit("environment_detected",{sessionId,hostOS,shellFamily,executionMode})},prmPatternDetected(sessionId,pattern,severity,category,stepRange){_internals15.emit("prm_pattern_detected",{sessionId,pattern,severity,category,stepRange})},prmCourseCorrectionInjected(sessionId,pattern,level){_internals15.emit("prm_course_correction_injected",{sessionId,pattern,level})},prmEscalationTriggered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_escalation_triggered",{sessionId,pattern,level,occurrenceCount})},prmHardStop(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop",{sessionId,pattern,level,occurrenceCount})},closeArchiveResult(data){_internals15.emit("close_archive_result",data)},residueHealth(data){_internals15.emit("residue_health",data)},trainingVaultHealth(data){_internals15.emit("training_vault_health",data)},contextTelemetryHealth(data){_internals15.emit("context_telemetry_health",data)},skillUsageHealth(data){_internals15.emit("skill_usage_health",data)},coreEventsHealth(data){_internals15.emit("core_events_health",data)},shellAuditHealth(data){_internals15.emit("shell_audit_health",data)},trajectoryHealth(data){_internals15.emit("trajectory_health",data)},prSubscriptionHealth(data){_internals15.emit("pr_subscription_health",data)},learningHealthAlarm(data){_internals15.emit("learning_health_alarm",data)},prmHardStopDelivered(sessionId,pattern,level,occurrenceCount){_internals15.emit("prm_hard_stop_delivered",{sessionId,pattern,level,occurrenceCount})},retrievalRouted(sessionId,data){_internals15.emit("retrieval_routed",{sessionId,...data})}},_internals15={telemetry,emit,rotateTelemetryIfNeeded,flushAndDrainTelemetry,heartbeatListenerCount:()=>_heartbeatListener!==null?1:0,createObservation,toLegacyTelemetryLine,canonicalLineContent}});import*as fs8 from"node:fs";import*as os4 from"node:os";import*as path14 from"node:path";function isAbsoluteDirectoryInput(value){return typeof value==="string"&&value.trim().length>0&&path14.isAbsolute(value)}function hasExplicitProjectBoundary(directory){if(!isAbsoluteDirectoryInput(directory))return!1;for(let marker of PROJECT_BOUNDARY_MARKERS)try{let stat5=_internals16.lstatSync(path14.join(directory,marker.name));if(!stat5.isSymbolicLink()&&marker.accepts(stat5))return!0}catch{}return!1}function isStrictPathDescendant(candidate,root){if(!isAbsoluteDirectoryInput(candidate)||!isAbsoluteDirectoryInput(root))return!1;let relative4=path14.relative(root,candidate);return relative4!==""&&relative4!==".."&&!relative4.startsWith(`..${path14.sep}`)&&!path14.isAbsolute(relative4)}function isMissingPathError(error49){let code=error49?.code;return code==="ENOENT"||code==="ENOTDIR"}function isWeakConfigContainerRoot(directory,dependencies){try{let resolved=dependencies.realpathSync(directory);return resolved===dependencies.realpathSync(os4.tmpdir())||resolved===dependencies.realpathSync(os4.homedir())}catch{let resolved=path14.resolve(directory);return resolved===path14.resolve(os4.tmpdir())||resolved===path14.resolve(os4.homedir())}}function projectIndicatorState(directory,dependencies,options={}){let allowConfigOnly=options.allowConfigOnly??!0;for(let indicator of PROJECT_ROOT_INDICATORS){if(!allowConfigOnly&&indicator===".opencode")continue;try{let indicatorStat=dependencies.statSync(path14.join(directory,indicator));if(indicatorStat.isFile()||indicatorStat.isDirectory())return"present"}catch(error49){if(!isMissingPathError(error49))return"inaccessible"}}return"absent"}function assertProjectRoot(directory,dependencies=fs8,artifactLabel="runtime state"){let resolved;try{resolved=dependencies.realpathSync(directory)}catch{throw warn(`[project-boundary] Cannot canonicalize directory "${directory}" — failing closed`),Error(`Cannot verify project root for "${directory}" — directory may not exist or is inaccessible`)}if(hasExplicitProjectBoundary(resolved))return;let current=resolved,depth=0;while(!0){if(depth>=MAX_PROJECT_ROOT_DEPTH)throw warn(`[project-boundary] Ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels for "${resolved}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor search exceeded ${MAX_PROJECT_ROOT_DEPTH} levels`);depth++;let parent=path14.dirname(current);if(parent===current)break;if(path14.dirname(parent)===parent){current=parent;continue}let parentSwarm=path14.join(parent,".swarm"),parentSwarmStat;try{parentSwarmStat=dependencies.statSync(parentSwarm)}catch(error49){if(isMissingPathError(error49)){current=parent;continue}throw warn(`[project-boundary] Cannot inspect ancestor state "${parentSwarm}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — ancestor state "${parentSwarm}" is inaccessible`)}if(parentSwarmStat.isDirectory()){let indicatorState=projectIndicatorState(parent,dependencies,{allowConfigOnly:!isWeakConfigContainerRoot(parent,dependencies)});if(indicatorState==="inaccessible")throw warn(`[project-boundary] Cannot inspect project indicators in ancestor "${parent}" — failing closed`),Error(`Cannot verify project root for "${resolved}" — project indicators in ancestor "${parent}" are inaccessible`);if(indicatorState==="present")throw warn(`[project-boundary] Rejecting write to subdirectory "${resolved}" — parent "${parent}" already contains .swarm/`),Error(`Cannot write ${artifactLabel} in "${resolved}" — parent directory "${parent}" already contains a .swarm/ folder. Runtime state must be written to the project root.`)}current=parent}}var MAX_PROJECT_ROOT_DEPTH=20,PROJECT_ROOT_INDICATORS,PROJECT_BOUNDARY_MARKERS,_internals16;var init_project_boundary=__esm(()=>{init_logger();PROJECT_ROOT_INDICATORS=["package.json",".git",".opencode","Cargo.toml","go.mod","pyproject.toml","Gemfile","composer.json","pom.xml","build.gradle","CMakeLists.txt"],PROJECT_BOUNDARY_MARKERS=[{name:".git",accepts:(stat5)=>stat5.isFile()||stat5.isDirectory()},{name:".opencode",accepts:(stat5)=>stat5.isDirectory()}];_internals16={lstatSync:fs8.lstatSync}});function backoffMs(attempt){let base=Math.min(BACKOFF_START_MS*2**attempt,BACKOFF_MAX_MS),jitter=base*BACKOFF_JITTER_RATIO*(Math.random()*2-1);return Math.max(1,Math.round(base+jitter))}async function withEvidenceLock(directory,evidencePath,agent,taskId,fn2,timeoutMs=60000){assertProjectRoot(directory);let deadline=Date.now()+timeoutMs,attempt=0;while(!0){let result=await tryAcquireLock(directory,evidencePath,agent,taskId);if(result.acquired){let lock=result.lock;if(attempt>0)emit("evidence_lock_stale_recovered",{directory,evidencePath,agent,taskId,attempt});emit("evidence_lock_acquired",{directory,evidencePath,agent,taskId,attempt});try{return await fn2()}finally{if(lock._release)try{await lock._release()}catch{}}}if(Date.now()>=deadline)throw new EvidenceLockTimeoutError(directory,evidencePath,agent,taskId,timeoutMs);emit("evidence_lock_contended",{directory,evidencePath,agent,taskId,attempt});let delay=Math.min(backoffMs(attempt),deadline-Date.now());if(delay>0)await new Promise((resolve10)=>setTimeout(resolve10,delay));attempt++}}var EvidenceLockTimeoutError,BACKOFF_START_MS=50,BACKOFF_MAX_MS=2000,BACKOFF_JITTER_RATIO=0.25;var init_lock=__esm(()=>{init_file_locks();init_telemetry();init_project_boundary();EvidenceLockTimeoutError=class EvidenceLockTimeoutError extends Error{directory;evidencePath;agent;taskId;constructor(directory,evidencePath,agent,taskId,timeoutMs){super(`Evidence lock timeout after ${timeoutMs}ms for ${evidencePath} (agent=${agent}, task=${taskId})`);this.name="EvidenceLockTimeoutError",this.directory=directory,this.evidencePath=evidencePath,this.agent=agent,this.taskId=taskId}}});import*as path15 from"node:path";function taskEvidenceRelPath(taskId){return path15.join("evidence",`${taskId}.json`)}function taskEvidencePath(directory,taskId){return path15.join(directory,".swarm",taskEvidenceRelPath(taskId))}async function atomicWriteFile(targetPath,content){await atomicWriteFileAnyRoot(targetPath,content)}function withTaskEvidenceLock(directory,taskId,agent,fn2){return withEvidenceLock(directory,taskEvidenceRelPath(taskId),agent,taskId,fn2)}var init_task_file=__esm(()=>{init_atomic_write();init_lock()});import*as os5 from"node:os";import*as path16 from"node:path";function resolveHiveDataDir(){let platform=process.platform,home=process.env.HOME||os5.homedir();if(platform==="win32")return path16.join(process.env.LOCALAPPDATA||path16.join(home,"AppData","Local"),"opencode-swarm","Data");if(platform==="darwin")return path16.join(home,"Library","Application Support","opencode-swarm");return path16.join(process.env.XDG_DATA_HOME||path16.join(home,".local","share"),"opencode-swarm")}function resolveHiveKnowledgePath(){return path16.join(resolveHiveDataDir(),"shared-learnings.jsonl")}function resolveHiveRejectedPath(){return path16.join(resolveHiveDataDir(),"shared-learnings-rejected.jsonl")}function resolveHiveEventsPath(){return path16.join(resolveHiveDataDir(),"shared-knowledge-events.jsonl")}var init_hive_paths=()=>{};function resolveRetentionCap(name,defaultValue){let override=overrides.get(name);if(override!==void 0&&Number.isFinite(override)&&override>=1)return override;return defaultValue}var overrides;var init_caps=__esm(()=>{overrides=new Map});import*as fs9 from"node:fs";import*as path17 from"node:path";function withFileLock(filePath,task){let key=path17.resolve(filePath),run=(appendChains.get(key)??Promise.resolve()).then(task,task),settled=run.then(()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)},()=>{if((appendChains.get(key)??settled)===settled)appendChains.delete(key)});return appendChains.set(key,settled),run}function sleep2(ms){return new Promise((resolve11)=>setTimeout(resolve11,ms))}async function renameWithRetry2(from,to){let lastError;for(let attempt=1;attempt<=RENAME_MAX_ATTEMPTS;attempt++)try{await fs9.promises.rename(from,to);return}catch(error49){lastError=error49;let code=typeof error49==="object"&&error49!==null&&"code"in error49?String(error49.code):"";if(code!=="EBUSY"&&code!=="EPERM"&&code!=="EEXIST"&&code!=="ENOTEMPTY")throw error49;if(attempt<RENAME_MAX_ATTEMPTS)await sleep2(RENAME_RETRY_DELAY_MS)}throw lastError instanceof Error?lastError:Error(String(lastError))}function wholeLines(content){return content.split(`
469
470
  `).map((line)=>line.trim()).filter((line)=>line.length>0)}function selectCompactionSurvivors(lines,opts){let kept=[],keptBytes=0;for(let i=lines.length-1;i>=0;i--){if(kept.length>=opts.maxEntries)break;let line=lines[i],lineBytes=Buffer.byteLength(`${line}
470
471
  `,"utf-8");if(kept.length>0&&opts.maxBytes!==void 0&&keptBytes+lineBytes>opts.maxBytes)break;kept.unshift(line),keptBytes+=lineBytes}return kept}async function appendAndCap(filePath,line,opts){let directory=path17.dirname(filePath);fs9.mkdirSync(directory,{recursive:!0});let record2=`${line.trim()}
471
472
  `,existing="";try{existing=await fs9.promises.readFile(filePath,"utf-8")}catch{}let combined=[...wholeLines(existing),line.trim()],survivors=selectCompactionSurvivors(combined,opts),dropped=combined.length-survivors.length;if(dropped>0){let compactedLines=combined.slice(dropped,combined.length-1),compacted=compactedLines.length>0?`${compactedLines.join(`
@@ -1056,7 +1057,7 @@ ${similar.map((cmd)=>` - /swarm ${cmd}`).join(`
1056
1057
 
1057
1058
  `)}async function executeSwarmCommand(args2){let{directory,agents,sessionID,tokens,packageRoot,config:config2,buildHelpText,policy,evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,activeAgentName,reviewAgentModelRegistry}=args2,text,resolved=resolveCommand(tokens);if(!resolved)text=tokens.length===0&&buildHelpText?buildHelpText():formatCommandNotFound(tokens);else{let policyResult=policy?.(resolved)??{allowed:!0};if(!policyResult.allowed)text=policyResult.message;else{try{let raw=await resolved.entry.handler({directory,args:resolved.remainingArgs,sessionID,agents,config:config2,packageRoot,source:"chat",evaluationModelDispatcher,reviewModelDispatcher,autoReviewConfig,activeAgentName,reviewAgentModelRegistry});text=isCommandFailure(raw)?raw.text:raw}catch(_err){let cmdName=tokens[0]||"unknown",errMsg=_err instanceof Error?_err.message:String(_err);text=`Error executing /swarm ${cmdName}: ${errMsg}`}if(resolved.warning)text=`${resolved.warning}
1058
1059
 
1059
- ${text}`}}return{text,resolved:resolved??void 0,canonicalKey:resolved?canonicalCommandKey(resolved):void 0}}var init_command_dispatch=__esm(()=>{init_registry2()});import{createHash as createHash36}from"node:crypto";import{existsSync as existsSync38,readFileSync as readFileSync28,statSync as statSync27}from"node:fs";import{join as join57}from"node:path";function flushPendingWrites(directory){try{_internals71.getGroupCommitWriter(directory).flushSync()}catch{}}function emptyHealth(){return{accepted:0,quarantined:0,dropped:0,last_error_category:null,last_error_at:null,last_flush_at:null,updated_at:null}}function noteDropped(directory,category){let h=_healthDeltas.get(directory)??emptyHealth();h.dropped+=1,h.last_error_category=category,h.last_error_at=new Date().toISOString(),_healthDeltas.set(directory,h)}function registerObservabilityEventSink(directory){try{let key=canonicalProjectKey(directory);if(_sinkListener!==null){if(_sinkDirectory===key)return;let previous=_sinkDirectory;if(previous!==null){if(projectDbExists(previous))flushPendingWrites(previous);_healthDeltas.delete(previous),_eventsSinceRetentionCheck.delete(previous),_eventsSinceHealthUpsert.delete(previous)}try{removeTelemetryListener(_sinkListener)}catch{}_sinkListener=null}_sinkDirectory=key,_sinkListener=(_event,_data,canonical)=>{let dir=_sinkDirectory;if(dir===null||canonical===void 0)return;try{appendObservabilityEventDb(dir,canonical)}catch(err){noteDropped(dir,err instanceof Error?err.constructor.name:"unknown")}},addTelemetryListener(_sinkListener)}catch{}}function isRecoveredDelegationEnd(canonical){if(canonical.kind!=="delegation_end")return!1;let raw=canonical.legacy?.raw;return raw?.recovered===!0&&typeof raw.record_id==="string"&&raw.record_id.length>0&&typeof raw.result==="string"}function recoveredEndEventId(canonical){if(!isRecoveredDelegationEnd(canonical))return canonical.eventId;let raw=canonical.legacy?.raw;return createHash36("sha256").update(`obs-recovered-end-v1\x00${raw.record_id}\x00${raw.result}`).digest("hex").slice(0,32)}function buildLiveRow(canonical){let violations=canonical.relationshipViolations??[],fallbackBuild=violations.includes("observation_build_failed"),payloadJson,quarantined=0,quarantineReason=null;try{payloadJson=JSON.stringify(canonical.legacy?.raw??{})}catch{payloadJson="{}",quarantined=1,quarantineReason="payload_unserializable"}if(quarantined===0&&payloadJson.length>MAX_EVENT_PAYLOAD_BYTES)payloadJson='{"truncated":true}',quarantined=1,quarantineReason="payload_oversize";if(quarantined===0&&fallbackBuild)quarantined=1,quarantineReason="observation_build_fallback";let trace=canonical.trace,workflow=canonical.workflow??{},lineage=canonical.lineage??{},outcome=canonical.outcome??{},policy=canonical.policy??{};return{columns:{event_id:recoveredEndEventId(canonical),kind:canonical.kind,category:canonical.category??null,severity:canonical.severity??null,occurred_at:canonical.occurredAt,writer_sequence:canonical.writerSequence??null,trace_id:trace?.traceId??null,span_id:trace?.spanId??null,host_session_id:workflow.hostSessionId??null,task_id:workflow.taskId??null,lane_id:workflow.laneId??null,batch_id:workflow.batchId??null,phase_id:workflow.phaseId??null,council_round_id:workflow.councilRoundId??null,project_ref:lineage.projectRef??null,outcome_status:outcome.status??null,retry_index:outcome.retryIndex??null,privacy_class:policy.privacyClass??null,sampled:policy.sampled===void 0?null:policy.sampled?1:0,payload_json:payloadJson,relationship_violations:violations.length>0?JSON.stringify(violations):null,quarantined,quarantine_reason:quarantineReason}}}function insertRow(db,columns,ingestedVia){db.run(INSERT_EVENT_SQL,[columns.event_id,columns.kind,columns.category,columns.severity,columns.occurred_at,columns.writer_sequence,columns.trace_id,columns.span_id,columns.host_session_id,columns.task_id,columns.lane_id,columns.batch_id,columns.phase_id,columns.council_round_id,columns.project_ref,columns.outcome_status,columns.retry_index,columns.privacy_class,columns.sampled,columns.payload_json,columns.relationship_violations,columns.quarantined,columns.quarantine_reason,ingestedVia])}function runRetentionIfOverCap(db){let count=db.query("SELECT COUNT(*) as count FROM observability_event").get()?.count??0;if(count<=MAX_OBSERVABILITY_EVENT_ROWS)return;let excess=count-MAX_OBSERVABILITY_EVENT_ROWS;db.run("DELETE FROM observability_event WHERE rowid IN (SELECT rowid FROM observability_event ORDER BY rowid ASC LIMIT ?)",[excess])}function upsertHealthDelta(db,root,flushed){let delta=_healthDeltas.get(root);if(delta===void 0)return;let now=new Date().toISOString();db.run(`INSERT INTO observability_sink_health (
1060
+ ${text}`}}return{text,resolved:resolved??void 0,canonicalKey:resolved?canonicalCommandKey(resolved):void 0}}var init_command_dispatch=__esm(()=>{init_registry2()});import{createHash as createHash36}from"node:crypto";import{existsSync as existsSync38,readFileSync as readFileSync28,statSync as statSync27}from"node:fs";import{join as join57}from"node:path";function isObservabilitySinkDisabled(){return process.env.SWARM_OBSERVABILITY_SINK_DISABLE==="1"}function lineHashOf(content){return createHash36("sha256").update(`${LINE_HASH_NAMESPACE}\x00${content}`).digest("hex")}function normalizeSegmentForLineHash(segment){return segment.endsWith("\r")?segment.slice(0,-1):segment}function flushPendingWrites(directory){try{_internals71.getGroupCommitWriter(directory).flushSync()}catch{}}function emptyHealth(){return{accepted:0,quarantined:0,dropped:0,last_error_category:null,last_error_at:null,last_flush_at:null,updated_at:null}}function noteDropped(directory,category){let h=_healthDeltas.get(directory)??emptyHealth();h.dropped+=1,h.last_error_category=category,h.last_error_at=new Date().toISOString(),_healthDeltas.set(directory,h)}function registerObservabilityEventSink(directory){try{let key=canonicalProjectKey(directory);if(isObservabilitySinkDisabled()){if(_sinkListener!==null){let previous=_sinkDirectory;if(previous!==null){if(projectDbExists(previous))flushPendingWrites(previous);_healthDeltas.delete(previous),_eventsSinceRetentionCheck.delete(previous),_eventsSinceHealthUpsert.delete(previous)}try{removeTelemetryListener(_sinkListener)}catch{}_sinkListener=null,_sinkDirectory=null}return}if(_sinkListener!==null){if(_sinkDirectory===key)return;let previous=_sinkDirectory;if(previous!==null){if(projectDbExists(previous))flushPendingWrites(previous);_healthDeltas.delete(previous),_eventsSinceRetentionCheck.delete(previous),_eventsSinceHealthUpsert.delete(previous)}try{removeTelemetryListener(_sinkListener)}catch{}_sinkListener=null}_sinkDirectory=key,_sinkListener=(_event,_data,canonical,canonicalContent)=>{let dir=_sinkDirectory;if(dir===null||canonical===void 0)return;if(isObservabilitySinkDisabled())return;try{appendObservabilityEventDb(dir,canonical,canonicalContent)}catch(err){noteDropped(dir,err instanceof DbWriteError?err.category:err instanceof Error?err.constructor.name:"unknown")}},addTelemetryListener(_sinkListener)}catch{}}function isRecoveredDelegationEnd(canonical){if(canonical.kind!=="delegation_end")return!1;let raw=canonical.legacy?.raw;return raw?.recovered===!0&&typeof raw.record_id==="string"&&raw.record_id.length>0&&typeof raw.result==="string"}function recoveredEndEventId(canonical){if(!isRecoveredDelegationEnd(canonical))return canonical.eventId;let raw=canonical.legacy?.raw;return createHash36("sha256").update(`obs-recovered-end-v1\x00${raw.record_id}\x00${raw.result}`).digest("hex").slice(0,32)}function buildLiveRow(canonical,canonicalContent){let violations=canonical.relationshipViolations??[],fallbackBuild=violations.includes("observation_build_failed"),payloadJson,quarantined=0,quarantineReason=null;try{payloadJson=JSON.stringify(canonical.legacy?.raw??{})}catch{payloadJson="{}",quarantined=1,quarantineReason="payload_unserializable"}if(quarantined===0&&payloadJson.length>MAX_EVENT_PAYLOAD_BYTES)payloadJson='{"truncated":true}',quarantined=1,quarantineReason="payload_oversize";if(quarantined===0&&fallbackBuild)quarantined=1,quarantineReason="observation_build_fallback";let trace=canonical.trace,workflow=canonical.workflow??{},lineage=canonical.lineage??{},outcome=canonical.outcome??{},policy=canonical.policy??{},lineHash=null;try{lineHash=lineHashOf(typeof canonicalContent==="string"?canonicalContent:_internals71.canonicalLineContent(canonical))}catch{lineHash=null}return{columns:{event_id:recoveredEndEventId(canonical),kind:canonical.kind,category:canonical.category??null,severity:canonical.severity??null,occurred_at:canonical.occurredAt,writer_sequence:canonical.writerSequence??null,trace_id:trace?.traceId??null,span_id:trace?.spanId??null,host_session_id:workflow.hostSessionId??null,task_id:workflow.taskId??null,lane_id:workflow.laneId??null,batch_id:workflow.batchId??null,phase_id:workflow.phaseId??null,council_round_id:workflow.councilRoundId??null,project_ref:lineage.projectRef??null,outcome_status:outcome.status??null,retry_index:outcome.retryIndex??null,privacy_class:policy.privacyClass??null,sampled:policy.sampled===void 0?null:policy.sampled?1:0,payload_json:payloadJson,relationship_violations:violations.length>0?JSON.stringify(violations):null,quarantined,quarantine_reason:quarantineReason,line_hash:lineHash}}}function insertRow(db,columns,ingestedVia){db.run(INSERT_EVENT_SQL,[columns.event_id,columns.kind,columns.category,columns.severity,columns.occurred_at,columns.writer_sequence,columns.trace_id,columns.span_id,columns.host_session_id,columns.task_id,columns.lane_id,columns.batch_id,columns.phase_id,columns.council_round_id,columns.project_ref,columns.outcome_status,columns.retry_index,columns.privacy_class,columns.sampled,columns.payload_json,columns.relationship_violations,columns.quarantined,columns.quarantine_reason,columns.line_hash,ingestedVia])}function runRetentionIfOverCap(db){let count=db.query("SELECT COUNT(*) as count FROM observability_event").get()?.count??0;if(count<=MAX_OBSERVABILITY_EVENT_ROWS)return;let excess=count-MAX_OBSERVABILITY_EVENT_ROWS;db.run("DELETE FROM observability_event WHERE rowid IN (SELECT rowid FROM observability_event ORDER BY rowid ASC LIMIT ?)",[excess])}function upsertHealthDelta(db,root,flushed){let delta=_healthDeltas.get(root);if(delta===void 0)return;let now=new Date().toISOString();db.run(`INSERT INTO observability_sink_health (
1060
1061
  id, accepted, quarantined, dropped,
1061
1062
  last_error_category, last_error_at, last_flush_at, updated_at
1062
1063
  ) VALUES (1, ?, ?, ?, ?, ?, ?, ?)
@@ -1067,14 +1068,14 @@ ${text}`}}return{text,resolved:resolved??void 0,canonicalKey:resolved?canonicalC
1067
1068
  last_error_category = excluded.last_error_category,
1068
1069
  last_error_at = excluded.last_error_at,
1069
1070
  last_flush_at = COALESCE(excluded.last_flush_at, last_flush_at),
1070
- updated_at = excluded.updated_at`,[delta.accepted,delta.quarantined,delta.dropped,delta.last_error_category,delta.last_error_at,flushed?now:null,now]),_healthDeltas.delete(root)}function appendObservabilityEventDb(directory,canonical){let root=canonicalProjectKey(directory),row=buildLiveRow(canonical),h=_healthDeltas.get(root)??emptyHealth();if(h.accepted+=1,row.columns.quarantined===1)h.quarantined+=1;_healthDeltas.set(root,h);let eventsSinceCheck=(_eventsSinceRetentionCheck.get(root)??0)+1;_eventsSinceRetentionCheck.set(root,eventsSinceCheck);let eventsSinceHealth=(_eventsSinceHealthUpsert.get(root)??0)+1;_eventsSinceHealthUpsert.set(root,eventsSinceHealth),_internals71.getGroupCommitWriter(root).enqueue({durability:DURABILITY_CLASSES.observability_event,run:(db)=>{if(insertRow(db,row.columns,"live"),eventsSinceCheck>=RETENTION_CHECK_INTERVAL)_eventsSinceRetentionCheck.set(root,0),runRetentionIfOverCap(db);if(eventsSinceHealth>=HEALTH_UPSERT_INTERVAL)_eventsSinceHealthUpsert.set(root,0),upsertHealthDelta(db,root,!0)}})}function syntheticImportEventId(line){return createHash36("sha256").update(`${IMPORT_ID_NAMESPACE}\x00${line}`).digest("hex")}function unparseableImportRow(line,reason){return{columns:{event_id:syntheticImportEventId(line),kind:"unknown",category:null,severity:null,occurred_at:new Date().toISOString(),writer_sequence:null,trace_id:null,span_id:null,host_session_id:null,task_id:null,lane_id:null,batch_id:null,phase_id:null,council_round_id:null,project_ref:null,outcome_status:null,retry_index:null,privacy_class:null,sampled:null,payload_json:line.length>MAX_EVENT_PAYLOAD_BYTES?'{"truncated":true}':JSON.stringify({raw_line:line}),relationship_violations:null,quarantined:1,quarantine_reason:reason},quarantined:!0}}function buildImportRow(line){if(line.trim().length===0)return null;if(line.length>MAX_IMPORT_LINE_BYTES)return unparseableImportRow(line,"import_oversize_line");let parsed;try{parsed=JSON.parse(line)}catch{return unparseableImportRow(line,"import_unparseable_line")}let workflow=_internals71.extractWorkflowIds(parsed),timestamp=typeof parsed.timestamp==="string"?parsed.timestamp:null,kind=typeof parsed.event==="string"&&parsed.event.length>0?parsed.event:"unknown",payloadJson=JSON.stringify(parsed);return{columns:{event_id:syntheticImportEventId(line),kind,category:null,severity:null,occurred_at:timestamp??new Date().toISOString(),writer_sequence:null,trace_id:null,span_id:null,host_session_id:workflow.hostSessionId??null,task_id:workflow.taskId??null,lane_id:workflow.laneId??null,batch_id:workflow.batchId??null,phase_id:workflow.phaseId??null,council_round_id:workflow.councilRoundId??null,project_ref:null,outcome_status:null,retry_index:null,privacy_class:null,sampled:null,payload_json:payloadJson.length>MAX_EVENT_PAYLOAD_BYTES?'{"truncated":true}':payloadJson,relationship_violations:null,quarantined:timestamp===null?1:0,quarantine_reason:timestamp===null?"import_missing_timestamp":null},quarantined:timestamp===null}}function syncObservabilityImport(directory){flushPendingWrites(directory);let root=canonicalProjectKey(directory),result={imported:0,quarantined:0,skippedUnchanged:!0};for(let fileName of LEGACY_STREAM_FILES){let filePath=join57(root,".swarm",fileName),stats2;try{let st=statSync27(filePath);stats2={size:st.size,mtimeMs:st.mtimeMs}}catch{continue}let db=_internals71.getProjectDb(directory),marker=db.query("SELECT fingerprint_size, fingerprint_mtime_ms, lines_seen FROM observability_import WHERE source = ?").get(fileName);if(marker!==null&&marker!==void 0&&marker.fingerprint_size===stats2.size&&marker.fingerprint_mtime_ms===stats2.mtimeMs)continue;result.skippedUnchanged=!1;let content;try{content=readFileSync28(filePath,"utf-8")}catch{continue}let lines=content.split(`
1071
- `),contentLineCount=lines.length>0&&lines[lines.length-1]===""?lines.length-1:lines.length,start=marker!==null&&marker!==void 0&&contentLineCount>=marker.lines_seen?marker.lines_seen:0,rows=[];for(let i=start;i<lines.length;i++){let built=buildImportRow(lines[i]);if(built===null)continue;rows.push(built)}let imported=rows.length,quarantined=rows.filter((r)=>r.quarantined).length;db.run("BEGIN IMMEDIATE");try{for(let row of rows)insertRow(db,row.columns,"import");db.run(`INSERT INTO observability_import (source, fingerprint_size, fingerprint_mtime_ms, lines_seen, imported_at)
1071
+ updated_at = excluded.updated_at`,[delta.accepted,delta.quarantined,delta.dropped,delta.last_error_category,delta.last_error_at,flushed?now:null,now]),_healthDeltas.delete(root)}function appendObservabilityEventDb(directory,canonical,canonicalContent){if(isObservabilitySinkDisabled())return;let root=canonicalProjectKey(directory),row=buildLiveRow(canonical,canonicalContent),h=_healthDeltas.get(root)??emptyHealth();if(h.accepted+=1,row.columns.quarantined===1)h.quarantined+=1;_healthDeltas.set(root,h);let eventsSinceCheck=(_eventsSinceRetentionCheck.get(root)??0)+1;_eventsSinceRetentionCheck.set(root,eventsSinceCheck);let eventsSinceHealth=(_eventsSinceHealthUpsert.get(root)??0)+1;_eventsSinceHealthUpsert.set(root,eventsSinceHealth),_internals71.getGroupCommitWriter(root).enqueue({durability:DURABILITY_CLASSES.observability_event,run:(db)=>{if(insertRow(db,row.columns,"live"),eventsSinceCheck>=RETENTION_CHECK_INTERVAL)_eventsSinceRetentionCheck.set(root,0),runRetentionIfOverCap(db);if(eventsSinceHealth>=HEALTH_UPSERT_INTERVAL)_eventsSinceHealthUpsert.set(root,0),upsertHealthDelta(db,root,!0)}})}function syntheticImportEventId(line){return createHash36("sha256").update(`${IMPORT_ID_NAMESPACE}\x00${line}`).digest("hex")}function unparseableImportRow(line,reason){return{columns:{event_id:syntheticImportEventId(line),kind:"unknown",category:null,severity:null,occurred_at:new Date().toISOString(),writer_sequence:null,trace_id:null,span_id:null,host_session_id:null,task_id:null,lane_id:null,batch_id:null,phase_id:null,council_round_id:null,project_ref:null,outcome_status:null,retry_index:null,privacy_class:null,sampled:null,payload_json:line.length>MAX_EVENT_PAYLOAD_BYTES?'{"truncated":true}':JSON.stringify({raw_line:line}),relationship_violations:null,quarantined:1,quarantine_reason:reason,line_hash:null},quarantined:!0,contentHash:lineHashOf(normalizeSegmentForLineHash(line))}}function buildImportRow(line){if(line.trim().length===0)return null;if(line.length>MAX_IMPORT_LINE_BYTES)return unparseableImportRow(line,"import_oversize_line");let parsed;try{parsed=JSON.parse(line)}catch{return unparseableImportRow(line,"import_unparseable_line")}let workflow=_internals71.extractWorkflowIds(parsed),timestamp=typeof parsed.timestamp==="string"?parsed.timestamp:null,kind=typeof parsed.event==="string"&&parsed.event.length>0?parsed.event:"unknown",payloadJson=JSON.stringify(parsed);return{columns:{event_id:syntheticImportEventId(line),kind,category:null,severity:null,occurred_at:timestamp??new Date().toISOString(),writer_sequence:null,trace_id:null,span_id:null,host_session_id:workflow.hostSessionId??null,task_id:workflow.taskId??null,lane_id:workflow.laneId??null,batch_id:workflow.batchId??null,phase_id:workflow.phaseId??null,council_round_id:workflow.councilRoundId??null,project_ref:null,outcome_status:null,retry_index:null,privacy_class:null,sampled:null,payload_json:payloadJson.length>MAX_EVENT_PAYLOAD_BYTES?'{"truncated":true}':payloadJson,relationship_violations:null,quarantined:timestamp===null?1:0,quarantine_reason:timestamp===null?"import_missing_timestamp":null,line_hash:null},quarantined:timestamp===null,contentHash:lineHashOf(normalizeSegmentForLineHash(line))}}function reconstructLiveRowLineHash(row){let{payload_json:payloadJson}=row;if(!payloadJson.startsWith("{")||!payloadJson.endsWith("}")||payloadJson.length<2)return null;let parsed;try{parsed=JSON.parse(payloadJson)}catch{return null}if(typeof parsed!=="object"||parsed===null||Array.isArray(parsed)||Object.keys(parsed).some((k)=>k==="timestamp"||k==="event"))return null;let body=payloadJson.slice(1,-1),line=body.length===0?`{"timestamp":${JSON.stringify(row.occurred_at)},"event":${JSON.stringify(row.kind)}}`:`{"timestamp":${JSON.stringify(row.occurred_at)},"event":${JSON.stringify(row.kind)},${body}}`;return lineHashOf(line)}function backfillLiveLineHashesOnce(db){let done=db.query("SELECT 1 as found FROM observability_import WHERE source = ?").get(LIVE_LINE_HASH_BACKFILL_MARKER);if(done!==void 0&&done!==null)return;let rows=db.query("SELECT rowid, occurred_at, kind, payload_json FROM observability_event WHERE line_hash IS NULL AND ingested_via = 'live' AND quarantined = 0").all();for(let row of rows){let hash3=reconstructLiveRowLineHash(row);if(hash3===null)continue;db.run("UPDATE observability_event SET line_hash = ? WHERE rowid = ?",[hash3,row.rowid])}db.run("INSERT INTO observability_import (source, fingerprint_size, fingerprint_mtime_ms, lines_seen, imported_at) VALUES (?, 0, 0, 0, ?)",[LIVE_LINE_HASH_BACKFILL_MARKER,new Date().toISOString()])}function filterImportCandidates(db,rows){let existing=new Set;for(let i=0;i<rows.length;i+=LINE_HASH_QUERY_CHUNK){let chunk=rows.slice(i,i+LINE_HASH_QUERY_CHUNK).map((r)=>r.contentHash),placeholders=chunk.map(()=>"?").join(", "),found=db.query(`SELECT line_hash FROM observability_event WHERE line_hash IN (${placeholders})`).all(...chunk);for(let f of found)existing.add(f.line_hash)}let toInsert=[],skippedLive=0;for(let row of rows){if(existing.has(row.contentHash)){skippedLive+=1;continue}toInsert.push({columns:row.columns,quarantined:row.quarantined})}return{toInsert,skippedLive}}function syncObservabilityImport(directory){flushPendingWrites(directory);let root=canonicalProjectKey(directory),result={imported:0,quarantined:0,skippedUnchanged:!0,skippedLive:0};for(let fileName of LEGACY_STREAM_FILES){let filePath=join57(root,".swarm",fileName),stats2;try{let st=statSync27(filePath);stats2={size:st.size,mtimeMs:st.mtimeMs}}catch{continue}let db=_internals71.getProjectDb(directory),marker=db.query("SELECT fingerprint_size, fingerprint_mtime_ms, lines_seen FROM observability_import WHERE source = ?").get(fileName);if(marker!==null&&marker!==void 0&&marker.fingerprint_size===stats2.size&&marker.fingerprint_mtime_ms===stats2.mtimeMs)continue;result.skippedUnchanged=!1;let content;try{content=readFileSync28(filePath,"utf-8")}catch{continue}let lines=content.split(`
1072
+ `),contentLineCount=lines.length>0&&lines[lines.length-1]===""?lines.length-1:lines.length,start=marker!==null&&marker!==void 0&&contentLineCount>=marker.lines_seen?marker.lines_seen:0,rows=[];for(let i=start;i<lines.length;i++){let built=buildImportRow(lines[i]);if(built===null)continue;rows.push(built)}db.run("BEGIN IMMEDIATE");try{backfillLiveLineHashesOnce(db);let{toInsert,skippedLive}=filterImportCandidates(db,rows);for(let row of toInsert)insertRow(db,row.columns,"import");db.run(`INSERT INTO observability_import (source, fingerprint_size, fingerprint_mtime_ms, lines_seen, imported_at)
1072
1073
  VALUES (?, ?, ?, ?, ?)
1073
1074
  ON CONFLICT(source) DO UPDATE SET
1074
1075
  fingerprint_size = excluded.fingerprint_size,
1075
1076
  fingerprint_mtime_ms = excluded.fingerprint_mtime_ms,
1076
1077
  lines_seen = excluded.lines_seen,
1077
- imported_at = excluded.imported_at`,[fileName,stats2.size,stats2.mtimeMs,contentLineCount,new Date().toISOString()]),runRetentionIfOverCap(db),db.run("COMMIT")}catch(err){try{db.run("ROLLBACK")}catch{}throw err}result.imported+=imported,result.quarantined+=quarantined}return result}function queryObservabilityEvents(directory,filter){flushPendingWrites(directory);let db=_internals71.getProjectDb(directory),where=["quarantined = 0"],params=[];if(filter.taskId!==void 0)where.push("task_id = ?"),params.push(filter.taskId);if(filter.sessionId!==void 0)where.push("host_session_id = ?"),params.push(filter.sessionId);if(filter.traceId!==void 0)where.push("trace_id = ?"),params.push(filter.traceId);if(filter.batchId!==void 0)where.push("batch_id = ?"),params.push(filter.batchId);if(filter.since!==void 0)where.push("occurred_at >= ?"),params.push(filter.since);let whereSql=where.join(" AND "),totalMatching=db.query(`SELECT COUNT(*) as count FROM observability_event WHERE ${whereSql}`).get(...params)?.count??0,rows=db.query(`SELECT rowid, event_id, kind, category, severity, occurred_at,
1078
+ imported_at = excluded.imported_at`,[fileName,stats2.size,stats2.mtimeMs,contentLineCount,new Date().toISOString()]),runRetentionIfOverCap(db),db.run("COMMIT"),result.imported+=toInsert.length,result.quarantined+=toInsert.filter((r)=>r.quarantined).length,result.skippedLive+=skippedLive}catch(err){try{db.run("ROLLBACK")}catch{}throw err}}return result}function queryObservabilityEvents(directory,filter){flushPendingWrites(directory);let db=_internals71.getProjectDb(directory),where=["quarantined = 0"],params=[];if(filter.taskId!==void 0)where.push("task_id = ?"),params.push(filter.taskId);if(filter.sessionId!==void 0)where.push("host_session_id = ?"),params.push(filter.sessionId);if(filter.traceId!==void 0)where.push("trace_id = ?"),params.push(filter.traceId);if(filter.batchId!==void 0)where.push("batch_id = ?"),params.push(filter.batchId);if(filter.since!==void 0)where.push("occurred_at >= ?"),params.push(filter.since);let whereSql=where.join(" AND "),totalMatching=db.query(`SELECT COUNT(*) as count FROM observability_event WHERE ${whereSql}`).get(...params)?.count??0,rows=db.query(`SELECT rowid, event_id, kind, category, severity, occurred_at,
1078
1079
  writer_sequence, trace_id, span_id, host_session_id, task_id,
1079
1080
  lane_id,
1080
1081
  batch_id, phase_id, council_round_id, project_ref, outcome_status,
@@ -1086,18 +1087,18 @@ ${text}`}}return{text,resolved:resolved??void 0,canonicalKey:resolved?canonicalC
1086
1087
  SUM(CASE WHEN ingested_via = 'live' THEN 1 ELSE 0 END) as live,
1087
1088
  SUM(CASE WHEN ingested_via = 'import' THEN 1 ELSE 0 END) as imported,
1088
1089
  SUM(quarantined) as quarantined
1089
- FROM observability_event`).get(),range=db.query("SELECT MIN(occurred_at) as earliest, MAX(occurred_at) as latest FROM observability_event WHERE quarantined = 0").get();return{liveRows:counts?.live??0,importedRows:counts?.imported??0,quarantinedRows:counts?.quarantined??0,totalRows:counts?.total??0,earliestOccurredAt:range?.earliest??null,latestOccurredAt:range?.latest??null}}function legacyStreamExists(directory){let root=canonicalProjectKey(directory);for(let fileName of LEGACY_STREAM_FILES)try{if(existsSync38(join57(root,".swarm",fileName)))return!0}catch{}return!1}var MAX_OBSERVABILITY_EVENT_ROWS=50000,RETENTION_CHECK_INTERVAL=512,HEALTH_UPSERT_INTERVAL=256,MAX_EVENT_PAYLOAD_BYTES=16384,LEGACY_STREAM_FILES,IMPORT_ID_NAMESPACE="obs-import-v1",MAX_IMPORT_LINE_BYTES=1048576,_sinkDirectory=null,_sinkListener=null,_healthDeltas,_eventsSinceRetentionCheck,_eventsSinceHealthUpsert,INSERT_EVENT_SQL=`INSERT OR IGNORE INTO observability_event (
1090
+ FROM observability_event`).get(),range=db.query("SELECT MIN(occurred_at) as earliest, MAX(occurred_at) as latest FROM observability_event WHERE quarantined = 0").get();return{liveRows:counts?.live??0,importedRows:counts?.imported??0,quarantinedRows:counts?.quarantined??0,totalRows:counts?.total??0,earliestOccurredAt:range?.earliest??null,latestOccurredAt:range?.latest??null}}function legacyStreamExists(directory){let root=canonicalProjectKey(directory);for(let fileName of LEGACY_STREAM_FILES)try{if(existsSync38(join57(root,".swarm",fileName)))return!0}catch{}return!1}var MAX_OBSERVABILITY_EVENT_ROWS=50000,RETENTION_CHECK_INTERVAL=512,HEALTH_UPSERT_INTERVAL=256,MAX_EVENT_PAYLOAD_BYTES=16384,LEGACY_STREAM_FILES,IMPORT_ID_NAMESPACE="obs-import-v1",MAX_IMPORT_LINE_BYTES=1048576,LINE_HASH_NAMESPACE="obs-line-v1",LINE_HASH_QUERY_CHUNK=500,LIVE_LINE_HASH_BACKFILL_MARKER="__live_line_hash_backfill__",_sinkDirectory=null,_sinkListener=null,_healthDeltas,_eventsSinceRetentionCheck,_eventsSinceHealthUpsert,INSERT_EVENT_SQL=`INSERT OR IGNORE INTO observability_event (
1090
1091
  event_id, kind, category, severity, occurred_at, writer_sequence,
1091
1092
  trace_id, span_id, host_session_id, task_id, lane_id, batch_id,
1092
1093
  phase_id, council_round_id, project_ref, outcome_status, retry_index,
1093
1094
  privacy_class, sampled, payload_json, relationship_violations,
1094
- quarantined, quarantine_reason, ingested_via
1095
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,MAX_REPORT_ROWS=5000,_internals71;var init_observability_event_store=__esm(()=>{init_legacy();init_telemetry();init_canonical_project();init_durability();init_group_commit_writer();init_project_db();LEGACY_STREAM_FILES=["telemetry.jsonl.1","telemetry.jsonl"];_healthDeltas=new Map,_eventsSinceRetentionCheck=new Map,_eventsSinceHealthUpsert=new Map;_internals71={getProjectDb,getGroupCommitWriter,extractWorkflowIds}});import{existsSync as existsSync39,mkdirSync as mkdirSync27,readFileSync as readFileSync29,renameSync as renameSync18,statSync as statSync28,writeFileSync as writeFileSync17}from"node:fs";import{join as join58}from"node:path";function toNanos(iso){let ms=typeof iso==="string"?Date.parse(iso):Number.NaN;if(!Number.isFinite(ms))return"0";return String(BigInt(Math.floor(ms))*1000000n)}function readMappedPath(event,path76){let raw=event.legacy?.raw;if(path76.startsWith("legacy.raw.")){let key=path76.slice(11);if(typeof raw!=="object"||raw===null)return;return raw[key]}if(path76==="kind")return event.kind;if(path76.startsWith("provenance."))return event.provenance?.[path76.slice(11)];if(path76.startsWith("workflow."))return event.workflow?.[path76.slice(9)];if(path76==="outcome.status")return event.outcome?.status;return}function projectOtlpAttributes(event,convention){if(event.policy?.privacyClass==="content")return{};let attributes={},entry=getCatalogEntry(event.kind),table=convention==="openinference"?OPENINFERENCE_ATTRIBUTES:OTEL_GENAI_ATTRIBUTES;if(entry!==void 0&&entry.otelMapping!=="none")for(let[path76,name]of Object.entries(table)){let value=readMappedPath(event,path76);if(typeof value==="number"&&Number.isFinite(value))attributes[name]=value;else if(typeof value==="boolean")attributes[name]=value;else if(typeof value==="string"&&value.length>0)attributes[name]=value.slice(0,MAX_ATTRIBUTE_STRING)}if(attributes["swarm.event.kind"]=event.kind,event.category!==void 0)attributes["swarm.event.category"]=event.category;if(event.severity!==void 0)attributes["swarm.event.severity"]=event.severity;if(event.outcome?.status!==void 0)attributes["swarm.outcome.status"]=event.outcome.status;if(typeof event.outcome?.durationMs==="number")attributes["swarm.outcome.duration_ms"]=event.outcome.durationMs;return attributes}function buildOtlpSpan(event,convention){if(event.policy?.privacyClass==="content")return null;return{traceId:event.trace?.traceId??"",spanId:event.trace?.spanId??"",name:event.kind,kind:1,startTimeUnixNano:toNanos(event.occurredAt),endTimeUnixNano:toNanos(event.observedAt),attributes:projectOtlpAttributes(event,convention)}}function spoolPath(directory){return join58(directory,OTLP_EXPORT_SPOOL_DIR,SPOOL_FILE)}function statePath(directory){return join58(directory,OTLP_EXPORT_SPOOL_DIR,STATE_FILE2)}function emptyState2(convention,circuitCooldownMs){return{v:STATE_VERSION,convention,accepted:0,exported:0,retried:0,dropped:{},lastErrorCategory:null,lastErrorAt:null,lastSuccessAt:null,consecutiveFailures:0,circuitOpenAt:null,nextAttemptAt:0,circuitCooldownMs}}function noteDrop(reason){if(_state===null)return;_state.dropped[reason]=(_state.dropped[reason]??0)+1,_state.lastErrorCategory=reason,_state.lastErrorAt=new Date().toISOString()}function atomicWrite2(path76,contents){let tmp=`${path76}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`;writeFileSync17(tmp,contents,"utf8");try{renameSync18(tmp,path76)}catch(err){try{if(existsSync39(tmp))writeFileSync17(path76,contents,"utf8")}catch{}let code=err?.code;if(code!==void 0&&code!=="EPERM"&&code!=="EBUSY")throw err}}function loadState2(directory){try{let raw=readFileSync29(statePath(directory),"utf-8"),parsed=JSON.parse(raw);if(parsed.v!==STATE_VERSION)return null;return parsed}catch{return null}}function persistState(){if(_directory===null||_state===null)return;try{mkdirSync27(join58(_directory,OTLP_EXPORT_SPOOL_DIR),{recursive:!0}),atomicWrite2(statePath(_directory),JSON.stringify(_state))}catch{}}function readSpoolLines(directory){try{return readFileSync29(spoolPath(directory),"utf-8").split(`
1095
+ quarantined, quarantine_reason, line_hash, ingested_via
1096
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,MAX_REPORT_ROWS=5000,_internals71;var init_observability_event_store=__esm(()=>{init_legacy();init_observe();init_telemetry();init_canonical_project();init_db_errors();init_durability();init_group_commit_writer();init_project_db();LEGACY_STREAM_FILES=["telemetry.jsonl.1","telemetry.jsonl"];_healthDeltas=new Map,_eventsSinceRetentionCheck=new Map,_eventsSinceHealthUpsert=new Map;_internals71={getProjectDb,getGroupCommitWriter,extractWorkflowIds,canonicalLineContent}});import{existsSync as existsSync39,mkdirSync as mkdirSync27,readFileSync as readFileSync29,renameSync as renameSync18,statSync as statSync28,writeFileSync as writeFileSync17}from"node:fs";import{join as join58}from"node:path";function toNanos(iso){let ms=typeof iso==="string"?Date.parse(iso):Number.NaN;if(!Number.isFinite(ms))return"0";return String(BigInt(Math.floor(ms))*1000000n)}function readMappedPath(event,path76){let raw=event.legacy?.raw;if(path76.startsWith("legacy.raw.")){let key=path76.slice(11);if(typeof raw!=="object"||raw===null)return;return raw[key]}if(path76==="kind")return event.kind;if(path76.startsWith("provenance."))return event.provenance?.[path76.slice(11)];if(path76.startsWith("workflow."))return event.workflow?.[path76.slice(9)];if(path76==="outcome.status")return event.outcome?.status;return}function projectOtlpAttributes(event,convention){if(event.policy?.privacyClass==="content")return{};let attributes={},entry=getCatalogEntry(event.kind),table=convention==="openinference"?OPENINFERENCE_ATTRIBUTES:OTEL_GENAI_ATTRIBUTES;if(entry!==void 0&&entry.otelMapping!=="none")for(let[path76,name]of Object.entries(table)){let value=readMappedPath(event,path76);if(typeof value==="number"&&Number.isFinite(value))attributes[name]=value;else if(typeof value==="boolean")attributes[name]=value;else if(typeof value==="string"&&value.length>0)attributes[name]=value.slice(0,MAX_ATTRIBUTE_STRING)}if(attributes["swarm.event.kind"]=event.kind,event.category!==void 0)attributes["swarm.event.category"]=event.category;if(event.severity!==void 0)attributes["swarm.event.severity"]=event.severity;if(event.outcome?.status!==void 0)attributes["swarm.outcome.status"]=event.outcome.status;if(typeof event.outcome?.durationMs==="number")attributes["swarm.outcome.duration_ms"]=event.outcome.durationMs;return attributes}function buildOtlpSpan(event,convention){if(event.policy?.privacyClass==="content")return null;return{traceId:event.trace?.traceId??"",spanId:event.trace?.spanId??"",name:event.kind,kind:1,startTimeUnixNano:toNanos(event.occurredAt),endTimeUnixNano:toNanos(event.observedAt),attributes:projectOtlpAttributes(event,convention)}}function spoolPath(directory){return join58(directory,OTLP_EXPORT_SPOOL_DIR,SPOOL_FILE)}function statePath(directory){return join58(directory,OTLP_EXPORT_SPOOL_DIR,STATE_FILE2)}function emptyState2(convention,circuitCooldownMs){return{v:STATE_VERSION,convention,accepted:0,exported:0,retried:0,dropped:{},lastErrorCategory:null,lastErrorAt:null,lastSuccessAt:null,consecutiveFailures:0,circuitOpenAt:null,nextAttemptAt:0,circuitCooldownMs}}function noteDrop(reason){if(_state===null)return;_state.dropped[reason]=(_state.dropped[reason]??0)+1,_state.lastErrorCategory=reason,_state.lastErrorAt=new Date().toISOString()}function atomicWrite2(path76,contents){let tmp=`${path76}.tmp-${process.pid}-${Math.random().toString(36).slice(2,8)}`;writeFileSync17(tmp,contents,"utf8");try{renameSync18(tmp,path76)}catch(err){try{if(existsSync39(tmp))writeFileSync17(path76,contents,"utf8")}catch{}let code=err?.code;if(code!==void 0&&code!=="EPERM"&&code!=="EBUSY")throw err}}function loadState2(directory){try{let raw=readFileSync29(statePath(directory),"utf-8"),parsed=JSON.parse(raw);if(parsed.v!==STATE_VERSION)return null;return parsed}catch{return null}}function persistState(){if(_directory===null||_state===null)return;try{mkdirSync27(join58(_directory,OTLP_EXPORT_SPOOL_DIR),{recursive:!0}),atomicWrite2(statePath(_directory),JSON.stringify(_state))}catch{}}function readSpoolLines(directory){try{return readFileSync29(spoolPath(directory),"utf-8").split(`
1096
1097
  `).filter((l)=>l.length>0)}catch{return[]}}function writeSpoolLines(directory,lines){mkdirSync27(join58(directory,OTLP_EXPORT_SPOOL_DIR),{recursive:!0}),atomicWrite2(spoolPath(directory),lines.length===0?"":`${lines.join(`
1097
1098
  `)}
1098
1099
  `)}function spoolByteSize(lines){return lines.reduce((sum,l)=>sum+Buffer.byteLength(l,"utf8")+1,0)}function appendSpoolRecord(record2){if(_directory===null||_config===null)return;let cfg=_config,line=JSON.stringify(record2),lines=readSpoolLines(_directory),now=record2.t,fresh=lines.filter((l)=>{try{let parsed=JSON.parse(l);if(now-parsed.t>cfg.spoolMaxAgeMs)return noteDrop("spool_age"),!1}catch{return noteDrop("spool_corrupt"),!1}return!0});fresh.push(line);let size=spoolByteSize(fresh);while(fresh.length>1&&size>cfg.spoolMaxBytes){let dropped=fresh.shift();if(dropped!==void 0)size-=Buffer.byteLength(dropped,"utf8")+1,noteDrop("spool_cap")}writeSpoolLines(_directory,fresh)}function endpointUrl(cfg){try{let url2=new URL(cfg.endpoint),host=url2.hostname.replace(/^\[|\]$/g,""),isLoopback=host==="localhost"||host==="127.0.0.1"||host==="::1";if(url2.protocol!=="https:"&&!isLoopback)return null;return`${cfg.endpoint.replace(/\/+$/,"")}/v1/traces`}catch{return null}}function classifyStatus(status){if(status===429||status===408)return"rate_limited";if(status>=500)return"server_error";return"rejected_permanent"}function backoffMs2(cfg,attempt){let exp=cfg.backoffBaseMs*2**attempt,jitter=Math.floor(Math.random()*Math.min(exp/2,1000));return Math.min(exp+jitter,cfg.backoffMaxMs)}async function postBatch(cfg,url2,batch){let controller=new AbortController,timer=setTimeout(()=>controller.abort(),cfg.requestTimeoutMs);try{let body=JSON.stringify({resourceSpans:[{resource:{attributes:[{key:"service.name",value:{stringValue:"opencode-swarm"}},{key:"swarm.mapping.version",value:{stringValue:cfg.convention==="openinference"?OPENINFERENCE_MAPPING_VERSION:OTEL_GENAI_MAPPING_VERSION}},{key:"swarm.schema.version",value:{intValue:1}}]},scopeSpans:[{scope:{name:"opencode-swarm",version:"opencode-swarm"},spans:batch}]}]}),headers={"content-type":"application/json",...cfg.headers??{}},response=await _internals72.fetch(url2,{method:"POST",headers,body,signal:controller.signal,redirect:"error"});if(response.ok){let declaredLength=Number(response.headers.get("content-length"));if(Number.isFinite(declaredLength)&&declaredLength>MAX_RESPONSE_BODY_BYTES)return{ok:!1,category:"malformed_response",retryAfterMs:null};try{let text=await response.text();if(text.length<=MAX_RESPONSE_BODY_BYTES&&text.includes('"partialSuccess"')){let parsed=JSON.parse(text),rejected=Number(parsed.partialSuccess?.rejectedSpans??0);if(rejected>0){if(_state!==null)_state.dropped.partial_rejected=(_state.dropped.partial_rejected??0)+rejected}}}catch{}return{ok:!0,category:null,retryAfterMs:null}}let retryAfterRaw=response.headers.get("retry-after"),retryAfterMs=null;if(retryAfterRaw!==null){let seconds=Number(retryAfterRaw);if(Number.isFinite(seconds)&&seconds>=0)retryAfterMs=Math.min(seconds*1000,cfg.backoffMaxMs)}return{ok:!1,category:classifyStatus(response.status),retryAfterMs}}catch{return{ok:!1,category:"unavailable",retryAfterMs:null}}finally{clearTimeout(timer)}}async function runFlushCycle(){if(_directory===null||_config===null||_state===null)return;let cfg=_config,url2=endpointUrl(cfg);if(url2===null)return;let now=_internals72.now();if(_state.circuitOpenAt!==null){if(now<_state.circuitOpenAt+cfg.circuitCooldownMs)return}if(now<_state.nextAttemptAt)return;for(let i=0;i<MAX_FLUSH_ITERATIONS;i++){let lines=readSpoolLines(_directory).slice(0,MAX_SPOOL_LINES_PER_FLUSH);if(lines.length===0){persistState();return}let nowMs=_internals72.now(),records=[],agedIds=new Set;for(let line of lines)try{let parsed=JSON.parse(line);if(nowMs-parsed.t>cfg.spoolMaxAgeMs){noteDrop("spool_age"),agedIds.add(parsed.id);continue}records.push({id:parsed.id,span:parsed.r})}catch{noteDrop("spool_corrupt")}if(records.length===0){if(agedIds.size>0)removeSpoolRecords(_directory,agedIds);persistState();return}let batchRecords=records.slice(0,cfg.batchSize),batch=batchRecords.map((r)=>r.span),batchIds=new Set(batchRecords.map((r)=>r.id)),outcome="failed";for(let attempt=0;attempt<=cfg.maxRetries;attempt++){if(attempt>0)_state.retried+=1;let result=await postBatch(cfg,url2,batch);if(result.ok){_state.exported+=batch.length,_state.consecutiveFailures=0,_state.circuitOpenAt=null,_state.lastSuccessAt=new Date().toISOString(),outcome="ok";break}if(result.category==="rejected_permanent"){for(let d=0;d<batch.length;d++)noteDrop("rejected_permanent");outcome="terminal";break}let wait=result.retryAfterMs!==null?result.retryAfterMs:backoffMs2(cfg,attempt);if(attempt<cfg.maxRetries)await _internals72.sleep(wait)}if(outcome!=="failed"){for(let aged of agedIds)batchIds.add(aged);removeSpoolRecords(_directory,batchIds);continue}if(_state.consecutiveFailures+=1,_state.consecutiveFailures>=cfg.circuitThreshold)_state.circuitOpenAt=_internals72.now();_state.nextAttemptAt=_internals72.now()+backoffMs2(cfg,cfg.maxRetries),noteDrop("flush_failed"),persistState();return}persistState()}function removeSpoolRecords(directory,ids){let lines=readSpoolLines(directory);if(lines.length===0)return;let kept=[],changed2=!1;for(let line of lines)try{let parsed=JSON.parse(line);if(ids.has(parsed.id)){changed2=!0;continue}kept.push(line)}catch{changed2=!0,noteDrop("spool_corrupt")}if(changed2)writeSpoolLines(directory,kept)}function flushSingleFlight(){if(_inFlight===null)_inFlight=runFlushCycle().catch(()=>{}).finally(()=>{_inFlight=null});return _inFlight}async function flushOtlpExporterForTesting(directory){if(directory!==_directory)return;await flushSingleFlight()}function stopTimer(){if(_flushTimer!==null)clearInterval(_flushTimer),_flushTimer=null}function registerOtlpExporter(directory,config2){try{if(_listener!==null){try{removeTelemetryListener(_listener)}catch{}_listener=null}if(stopTimer(),_active=!1,_config=null,_directory=null,_state=null,config2.enabled!==!0)return;if(process.env[KILL_SWITCH_ENV]==="1")return;if(endpointUrl(config2)===null)return;if(_directory=directory,_config=config2,_state=loadState2(directory)??emptyState2(config2.convention,config2.circuitCooldownMs),_state.convention=config2.convention,_state.circuitCooldownMs=config2.circuitCooldownMs,_listener=(_event,_data,canonical)=>{try{if(canonical===void 0)return;let span=buildOtlpSpan(canonical,config2.convention);if(span===null)return;if(appendSpoolRecord({v:SPOOL_RECORD_VERSION,id:canonical.eventId,t:_internals72.now(),r:span}),_state!==null)_state.accepted+=1}catch{noteDrop("listener_error")}},addTelemetryListener(_listener),_active=!0,_flushTimer=setInterval(()=>{flushSingleFlight()},config2.flushIntervalMs),typeof _flushTimer.unref==="function")_flushTimer.unref()}catch{_active=!1}}function isOtlpExporterActive(){return _active}function readOtlpExporterHealth(directory){let persisted=_directory===directory&&_state!==null?_state:loadState2(directory);if(persisted===null)return null;let cfg=_directory===directory?_config:null,spoolRecords=0,spoolBytes=0;try{spoolBytes=statSync28(spoolPath(directory)).size,spoolRecords=readSpoolLines(directory).length}catch{}let circuitOpen=persisted.circuitOpenAt!==null&&_internals72.now()<persisted.circuitOpenAt+(cfg?.circuitCooldownMs??persisted.circuitCooldownMs??60000);return{state:circuitOpen?"cooldown":_active&&_directory===directory?"active":"disabled",convention:persisted.convention,mappingVersion:persisted.convention==="openinference"?OPENINFERENCE_MAPPING_VERSION:OTEL_GENAI_MAPPING_VERSION,spoolRecords,spoolBytes,accepted:persisted.accepted,exported:persisted.exported,retried:persisted.retried,dropped:{...persisted.dropped},lastErrorCategory:persisted.lastErrorCategory,lastErrorAt:persisted.lastErrorAt,lastSuccessAt:persisted.lastSuccessAt,circuitOpen}}var OTLP_EXPORT_SPOOL_DIR=".swarm/otlp-export",SPOOL_FILE="spool.jsonl",STATE_FILE2="state.json",SPOOL_RECORD_VERSION=1,STATE_VERSION=1,MAX_FLUSH_ITERATIONS=100,MAX_ATTRIBUTE_STRING=128,MAX_SPOOL_LINES_PER_FLUSH=2048,MAX_RESPONSE_BODY_BYTES=1048576,KILL_SWITCH_ENV="SWARM_OTLP_EXPORT_DISABLE",_listener=null,_active=!1,_config=null,_directory=null,_state=null,_flushTimer=null,_inFlight=null,_internals72;var init_otlp_exporter=__esm(()=>{init_telemetry();init_catalog();init_otel_mapping();_internals72={fetch:(input,init)=>fetch(input,init),sleep:(ms)=>new Promise((resolve39)=>setTimeout(resolve39,ms)),now:()=>Date.now()}});function parseValueFlag(args2,flag){let found;for(let i=0;i<args2.length;i++){if(args2[i]!==flag)continue;if(found!==void 0)return{error:`${flag} may be passed at most once`};let value=args2[i+1];if(value===void 0||value.startsWith("--"))return{error:`${flag} requires a non-empty value`};found=value,i++}if(found!==void 0&&found.length===0)return{error:`${flag} requires a non-empty value`};return{value:found}}function parseReportArgs(args2){let known=new Set(["--task","--session","--trace","--run","--since","--json"]);for(let arg of args2)if(arg.startsWith("--")&&!known.has(arg))return{error:`Unrecognized argument: ${arg}
1099
1100
  ${USAGE}`};let task=parseValueFlag(args2,"--task");if(task.error)return{error:task.error};let session=parseValueFlag(args2,"--session");if(session.error)return{error:session.error};let trace=parseValueFlag(args2,"--trace");if(trace.error)return{error:trace.error};let run=parseValueFlag(args2,"--run");if(run.error)return{error:run.error};let since=parseValueFlag(args2,"--since");if(since.error)return{error:since.error};if(since.value!==void 0&&Number.isNaN(Date.parse(since.value)))return{error:`--since must be an ISO-8601 timestamp
1100
- ${USAGE}`};return{parsed:{filter:{...task.value!==void 0?{taskId:task.value}:{},...session.value!==void 0?{sessionId:session.value}:{},...trace.value!==void 0?{traceId:trace.value}:{},...run.value!==void 0?{batchId:run.value}:{},...since.value!==void 0?{since:since.value}:{}},json:args2.includes("--json")}}}function computePairing(rows){let begins=0,ends=0,recoveredEnds=0,openBegins=new Map;for(let row of rows)if(row.kind==="delegation_begin"){begins+=1;let key=`${row.host_session_id??""}\x00${JSON.parse(row.payload_json).agentName??""}\x00${row.task_id??""}`;openBegins.set(key,(openBegins.get(key)??0)+1)}else if(row.kind==="delegation_end"){ends+=1;let payload=JSON.parse(row.payload_json);if(payload.recovered===!0)recoveredEnds+=1;let key=`${payload.sessionId??""}\x00${payload.agentName??""}\x00${payload.taskId??""}`,open5=openBegins.get(key);if(open5!==void 0&&open5>0)openBegins.set(key,open5-1)}let unmatched=0;for(let count of openBegins.values())unmatched+=count;return{begins,ends,recoveredEnds,unmatchedBegins:unmatched}}function computeSavings(rows){let bySource=new Map;for(let row of rows){if(row.kind!=="context_source_attribution")continue;let payload=JSON.parse(row.payload_json),source=typeof payload.source==="string"?payload.source:"unknown",entry=bySource.get(source)??{source,calls:0,tokensReturned:0,tokensSavedEstimate:0};entry.calls+=1,entry.tokensReturned+=payload.tokensReturned??0,entry.tokensSavedEstimate+=payload.tokensSavedEstimate??0,bySource.set(source,entry)}return[...bySource.values()].sort((a,b)=>a.source<b.source?-1:a.source>b.source?1:0)}async function handleReportCommand(directory,args2){let{parsed,error:error49}=parseReportArgs(args2);if(parsed===void 0||error49!==void 0)return error49??USAGE;let coverage=readObservabilityCoverage(directory);if(coverage===null)return parsed.json?`[REPORT_JSON]${JSON.stringify({schemaVersion:REPORT_JSON_SCHEMA_VERSION,filters:parsed.filter,coverage:{unavailable:!0},timeline:[]})}[/REPORT_JSON]`:"No observability store found for this project yet — events land here once the swarm runs.";let importResult=syncObservabilityImport(directory),query=queryObservabilityEvents(directory,parsed.filter),pairing=computePairing(query.rows),savings=computeSavings(query.rows),timeline=query.rows.map((row)=>({occurredAt:row.occurred_at,kind:row.kind,sessionId:row.host_session_id,taskId:row.task_id,traceId:row.trace_id,outcome:row.outcome_status})),health=readObservabilitySinkHealth(directory),otlpHealth=readOtlpExporterHealth(directory),postImportCoverage=readObservabilityCoverage(directory)??coverage,report={schemaVersion:REPORT_JSON_SCHEMA_VERSION,filters:parsed.filter,coverage:{...postImportCoverage,importedThisSync:importResult.imported,quarantinedThisSync:importResult.quarantined,rowCap:MAX_REPORT_ROWS,truncated:query.truncated,totalMatching:query.totalMatching,legacyWindow:"current telemetry.jsonl generations only"},pairing:{...pairing,note:"unmatched begins are disclosed, never fabricated into ends"},savings:savings.map((s)=>({...s,estimate:!0})),health,otlpExport:otlpHealth,timeline};if(parsed.json)return`[REPORT_JSON]${JSON.stringify(report)}[/REPORT_JSON]`;let lines=[];if(lines.push("## Swarm Observability Report"),lines.push(""),lines.push(`**Coverage** — ${postImportCoverage.totalRows} events (live ${postImportCoverage.liveRows}, imported ${postImportCoverage.importedRows}; quarantined ${postImportCoverage.quarantinedRows})`),postImportCoverage.earliestOccurredAt!==null)lines.push(`Window: ${postImportCoverage.earliestOccurredAt} → ${postImportCoverage.latestOccurredAt} (import covers current telemetry.jsonl generations only)`);if(query.truncated)lines.push(`⚠ Timeline truncated to ${MAX_REPORT_ROWS} rows (${query.totalMatching} matched the filters).`);if(lines.push(""),lines.push(`**Delegation pairing** — ${pairing.begins} begins / ${pairing.ends} ends${pairing.recoveredEnds>0?` (${pairing.recoveredEnds} recovered)`:""}; ${pairing.unmatchedBegins} unmatched begin(s) disclosed`),lines.push(""),savings.length>0){lines.push("**Context-source savings (estimates)**"),lines.push(""),lines.push("| Source | Calls | Tokens returned | Est. saved |"),lines.push("| --- | --- | --- | --- |");for(let s of savings){let safeSource=s.source.replace(/\|/g,"\\|").replace(/\r?\n/g," ");lines.push(`| ${safeSource} | ${s.calls} | ${s.tokensReturned} | ${s.tokensSavedEstimate} |`)}lines.push("")}if(lines.push(`**Sink health** — accepted ${health?.accepted??0}, quarantined ${health?.quarantined??0}, dropped ${health?.dropped??0}`),otlpHealth!==null){let drops=Object.entries(otlpHealth.dropped).map(([reason,count])=>`${count} ${reason}`).join(", ");lines.push(""),lines.push(`**OTLP export** — ${otlpHealth.state}${otlpHealth.circuitOpen?" (circuit open, cooldown)":""}; ${otlpHealth.convention} mapping ${otlpHealth.mappingVersion}; spooled ${otlpHealth.spoolRecords} record(s) / ${otlpHealth.spoolBytes} B; accepted ${otlpHealth.accepted}, exported ${otlpHealth.exported}, retried ${otlpHealth.retried}, dropped ${drops.length>0?drops:"0"}`)}lines.push(""),lines.push(`**Timeline** — ${timeline.length} event(s)`);for(let entry of timeline.slice(0,50))lines.push(`- ${entry.occurredAt} ${entry.kind}${entry.taskId!==null?` task=${entry.taskId}`:""}${entry.sessionId!==null?` session=${entry.sessionId}`:""}${entry.outcome!==null?` outcome=${entry.outcome}`:""}`);if(timeline.length>50)lines.push(`- … ${timeline.length-50} more (use --json or narrower filters)`);return lines.join(`
1101
+ ${USAGE}`};return{parsed:{filter:{...task.value!==void 0?{taskId:task.value}:{},...session.value!==void 0?{sessionId:session.value}:{},...trace.value!==void 0?{traceId:trace.value}:{},...run.value!==void 0?{batchId:run.value}:{},...since.value!==void 0?{since:since.value}:{}},json:args2.includes("--json")}}}function computePairing(rows){let begins=0,ends=0,recoveredEnds=0,openBegins=new Map;for(let row of rows)if(row.kind==="delegation_begin"){begins+=1;let key=`${row.host_session_id??""}\x00${JSON.parse(row.payload_json).agentName??""}\x00${row.task_id??""}`;openBegins.set(key,(openBegins.get(key)??0)+1)}else if(row.kind==="delegation_end"){ends+=1;let payload=JSON.parse(row.payload_json);if(payload.recovered===!0)recoveredEnds+=1;let key=`${payload.sessionId??""}\x00${payload.agentName??""}\x00${payload.taskId??""}`,open5=openBegins.get(key);if(open5!==void 0&&open5>0)openBegins.set(key,open5-1)}let unmatched=0;for(let count of openBegins.values())unmatched+=count;return{begins,ends,recoveredEnds,unmatchedBegins:unmatched}}function computeSavings(rows){let bySource=new Map;for(let row of rows){if(row.kind!=="context_source_attribution")continue;let payload=JSON.parse(row.payload_json),source=typeof payload.source==="string"?payload.source:"unknown",entry=bySource.get(source)??{source,calls:0,tokensReturned:0,tokensSavedEstimate:0};entry.calls+=1,entry.tokensReturned+=payload.tokensReturned??0,entry.tokensSavedEstimate+=payload.tokensSavedEstimate??0,bySource.set(source,entry)}return[...bySource.values()].sort((a,b)=>a.source<b.source?-1:a.source>b.source?1:0)}async function handleReportCommand(directory,args2){let{parsed,error:error49}=parseReportArgs(args2);if(parsed===void 0||error49!==void 0)return error49??USAGE;let coverage=readObservabilityCoverage(directory);if(coverage===null)return parsed.json?`[REPORT_JSON]${JSON.stringify({schemaVersion:REPORT_JSON_SCHEMA_VERSION,filters:parsed.filter,coverage:{unavailable:!0},timeline:[]})}[/REPORT_JSON]`:"No observability store found for this project yet — events land here once the swarm runs.";let importResult=syncObservabilityImport(directory),query=queryObservabilityEvents(directory,parsed.filter),pairing=computePairing(query.rows),savings=computeSavings(query.rows),timeline=query.rows.map((row)=>({occurredAt:row.occurred_at,kind:row.kind,sessionId:row.host_session_id,taskId:row.task_id,traceId:row.trace_id,outcome:row.outcome_status})),health=readObservabilitySinkHealth(directory),otlpHealth=readOtlpExporterHealth(directory),postImportCoverage=readObservabilityCoverage(directory)??coverage,report={schemaVersion:REPORT_JSON_SCHEMA_VERSION,filters:parsed.filter,coverage:{...postImportCoverage,importedThisSync:importResult.imported,quarantinedThisSync:importResult.quarantined,skippedLiveThisSync:importResult.skippedLive,rowCap:MAX_REPORT_ROWS,truncated:query.truncated,totalMatching:query.totalMatching,legacyWindow:"current telemetry.jsonl generations only"},pairing:{...pairing,note:"unmatched begins are disclosed, never fabricated into ends"},savings:savings.map((s)=>({...s,estimate:!0})),health,otlpExport:otlpHealth,timeline};if(parsed.json)return`[REPORT_JSON]${JSON.stringify(report)}[/REPORT_JSON]`;let lines=[];if(lines.push("## Swarm Observability Report"),lines.push(""),lines.push(`**Coverage** — ${postImportCoverage.totalRows} events (live ${postImportCoverage.liveRows}, imported ${postImportCoverage.importedRows}; quarantined ${postImportCoverage.quarantinedRows})`),postImportCoverage.earliestOccurredAt!==null)lines.push(`Window: ${postImportCoverage.earliestOccurredAt} → ${postImportCoverage.latestOccurredAt} (import covers current telemetry.jsonl generations only)`);if(query.truncated)lines.push(`⚠ Timeline truncated to ${MAX_REPORT_ROWS} rows (${query.totalMatching} matched the filters).`);if(lines.push(""),lines.push(`**Delegation pairing** — ${pairing.begins} begins / ${pairing.ends} ends${pairing.recoveredEnds>0?` (${pairing.recoveredEnds} recovered)`:""}; ${pairing.unmatchedBegins} unmatched begin(s) disclosed`),lines.push(""),savings.length>0){lines.push("**Context-source savings (estimates)**"),lines.push(""),lines.push("| Source | Calls | Tokens returned | Est. saved |"),lines.push("| --- | --- | --- | --- |");for(let s of savings){let safeSource=s.source.replace(/\|/g,"\\|").replace(/\r?\n/g," ");lines.push(`| ${safeSource} | ${s.calls} | ${s.tokensReturned} | ${s.tokensSavedEstimate} |`)}lines.push("")}if(lines.push(`**Sink health** — accepted ${health?.accepted??0}, quarantined ${health?.quarantined??0}, dropped ${health?.dropped??0}`),otlpHealth!==null){let drops=Object.entries(otlpHealth.dropped).map(([reason,count])=>`${count} ${reason}`).join(", ");lines.push(""),lines.push(`**OTLP export** — ${otlpHealth.state}${otlpHealth.circuitOpen?" (circuit open, cooldown)":""}; ${otlpHealth.convention} mapping ${otlpHealth.mappingVersion}; spooled ${otlpHealth.spoolRecords} record(s) / ${otlpHealth.spoolBytes} B; accepted ${otlpHealth.accepted}, exported ${otlpHealth.exported}, retried ${otlpHealth.retried}, dropped ${drops.length>0?drops:"0"}`)}lines.push(""),lines.push(`**Timeline** — ${timeline.length} event(s)`);for(let entry of timeline.slice(0,50))lines.push(`- ${entry.occurredAt} ${entry.kind}${entry.taskId!==null?` task=${entry.taskId}`:""}${entry.sessionId!==null?` session=${entry.sessionId}`:""}${entry.outcome!==null?` outcome=${entry.outcome}`:""}`);if(timeline.length>50)lines.push(`- … ${timeline.length-50} more (use --json or narrower filters)`);return lines.join(`
1101
1102
  `)}var REPORT_JSON_SCHEMA_VERSION=1,USAGE;var init_report=__esm(()=>{init_observability_event_store();init_otlp_exporter();USAGE=["Usage: /swarm report [--task <id>] [--session <id>] [--trace <id>]"," [--run <batchId>] [--since <ISO-8601>] [--json]"," --run filters the lane/dispatch batch axis (workflow.batchId)."].join(`
1102
1103
  `)});function lazySet(getValues){let cached2=null,ensure=()=>{if(cached2===null)cached2=new Set(getValues());return cached2};return new Proxy({},{get(_target,prop){let set2=ensure(),value=Reflect.get(set2,prop);return typeof value==="function"?value.bind(set2):value}})}function lazyArray(getValues){let cached2=null,ensure=()=>{if(cached2===null)cached2=getValues();return cached2};return new Proxy([],{get(_target,prop){let arr=ensure(),value=Reflect.get(arr,prop);return typeof value==="function"?value.bind(arr):value}})}function classifySwarmCommandToolUse(resolved){let canonicalKey=canonicalCommandKey(resolved),args2=resolved.remainingArgs;if(!SWARM_COMMAND_TOOL_ALLOWLIST.has(canonicalKey)){if(HUMAN_ONLY_SWARM_COMMANDS.has(canonicalKey))return{allowed:!1,message:`/swarm ${canonicalKey} is a human-only command. Present the situation to the user and ask them to run \`/swarm ${canonicalKey}\` themselves (or \`bunx opencode-swarm run ${canonicalKey}\` from a terminal). `+"You MUST NOT run it yourself via Bash, swarm_command, or any other tool — "+"the runtime guardrails are configured to block such attempts; if you observe a bypass, stop and report it to the user."};return{allowed:!1,message:`/swarm ${canonicalKey} is not available through the chat tool yet.
1103
1104
 
@@ -1249,14 +1250,14 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1249
1250
  `),!0}catch(error49){return warn(`[background] reservation write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}}function reservationOwnerKey(input){return input.planTaskId===null?`call:${input.parentSessionId}:${input.callID}`:`task:${input.parentSessionId}:${input.planTaskId}`}function isActiveCoderOwner(record2){if(record2.normalizedAgent!=="coder"||record2.status==="consumed")return!1;if(record2.status==="pending"||record2.status==="running"||record2.status==="completed"||record2.status==="ingestion_error")return!0;if(record2.coderSettlement?.state==="preserved")return!0;return record2.worktree!==void 0}async function scanDurableCoderOwners(directory){let fallbackScan=await scanDelegationFallbacksForRecovery(directory);if(fallbackScan.status==="uncertain")return fallbackScan;let primaryScan=scanDelegationsForRecovery(directory);if(primaryScan.status==="uncertain")return primaryScan;let recordsByCorrelation=new Map;for(let artifact of fallbackScan.owners)recordsByCorrelation.set(artifact.correlationId,artifact.record);let primaryByCorrelation=new Map,primaryByReservationId=new Map;for(let record2 of primaryScan.owners){if(primaryByCorrelation.set(record2.correlationId,record2),record2.coderReservationId){let owners=primaryByReservationId.get(record2.coderReservationId)??[];owners.push(record2),primaryByReservationId.set(record2.coderReservationId,owners)}recordsByCorrelation.set(record2.correlationId,record2)}return{status:"ok",recordsByCorrelation,primaryByCorrelation,primaryByReservationId}}function exactReservationOwnerCoordinates(reservation,record2){return record2.coderReservationId===reservation.reservationId&&record2.parentSessionId===reservation.parentSessionId&&record2.planTaskId===reservation.planTaskId&&record2.callID===reservation.callID}function exactReservationRecordMatch(reservation,record2){return exactReservationOwnerCoordinates(reservation,record2)&&record2.correlationId===reservation.correlationId}function findExactPrimaryReservationOwner(reservation,ownerScan){if(reservation.correlationId!==null){let primary=ownerScan.primaryByCorrelation.get(reservation.correlationId);return primary&&exactReservationRecordMatch(reservation,primary)?primary:null}let exactOwners=(ownerScan.primaryByReservationId.get(reservation.reservationId)??[]).filter((record2)=>exactReservationOwnerCoordinates(reservation,record2));return exactOwners.length===1?exactOwners[0]:null}function hasProvenReleasedReservationOwner(record2){if(record2.status==="consumed")return!0;return record2.worktree===void 0&&(record2.status==="error"||record2.status==="cancelled")&&record2.terminalResult?.status===record2.status}function validateReservationIdentity(input){return typeof input.parentSessionId==="string"&&input.parentSessionId.length>0&&input.parentSessionId.length<=256&&input.parentSessionId.trim()===input.parentSessionId&&typeof input.callID==="string"&&input.callID.length>0&&input.callID.length<=256&&input.callID.trim()===input.callID&&(input.planTaskId===null||typeof input.planTaskId==="string"&&input.planTaskId.length>0&&input.planTaskId.length<=256&&input.planTaskId.trim()===input.planTaskId)}async function reserveBackgroundCoderSlot(directory,input){if(!validateReservationIdentity(input)||!Number.isInteger(input.maxConcurrent)||input.maxConcurrent<1||input.maxConcurrent>64||(input.occupiedTaskIds?.length??0)>64||!isValidReservationGeneration(input.generation))return{ok:!1,reason:"invalid"};let occupiedTaskIds=new Set;for(let taskId of input.occupiedTaskIds??[]){if(typeof taskId!=="string"||taskId.length===0||taskId.length>256||taskId.trim()!==taskId)return{ok:!1,reason:"invalid"};occupiedTaskIds.add(taskId)}try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT2,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:reservationScan.reason};let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return{ok:!1,reason:"uncertain",detail:ownerScan.reason};let reservations=reservationScan.reservations.filter((reservation2)=>{let primary=findExactPrimaryReservationOwner(reservation2,ownerScan);return!(primary&&hasProvenReleasedReservationOwner(primary))});if(reservations.length!==reservationScan.reservations.length&&!await writeBackgroundCoderReservations(directory,reservations))return{ok:!1,reason:"uncertain",detail:"finished reservation reconciliation could not be persisted"};let activeOwnerKeys=new Set;for(let taskId of occupiedTaskIds)activeOwnerKeys.add(reservationOwnerKey({parentSessionId:input.parentSessionId,planTaskId:taskId,callID:""}));for(let reservation2 of reservations)if(reservation2.parentSessionId===input.parentSessionId)activeOwnerKeys.add(reservationOwnerKey(reservation2));for(let record2 of ownerScan.recordsByCorrelation.values())if(record2.parentSessionId===input.parentSessionId&&isActiveCoderOwner(record2))activeOwnerKeys.add(reservationOwnerKey({parentSessionId:record2.parentSessionId,planTaskId:record2.planTaskId,callID:record2.callID}));let reservationId=buildBackgroundCoderReservationId(input),existing=reservations.find((reservation2)=>reservation2.reservationId===reservationId);if(existing)return{ok:!1,reason:input.planTaskId===null?"duplicate_call":"duplicate_task",activeCount:activeOwnerKeys.size,existing};let incomingOwnerKey=reservationOwnerKey(input);if(input.planTaskId!==null&&activeOwnerKeys.has(incomingOwnerKey))return{ok:!1,reason:"duplicate_task",activeCount:activeOwnerKeys.size};if(activeOwnerKeys.size>=input.maxConcurrent)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size};if(reservations.length>=MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)return{ok:!1,reason:"capacity",activeCount:activeOwnerKeys.size,detail:"durable reservation store is at its hard safety cap"};let now=input.now??Date.now(),leaseMs=clampReservationLeaseMs(input.leaseMs),reservation={reservationId,parentSessionId:input.parentSessionId,planTaskId:input.planTaskId,callID:input.callID,state:"reserved",correlationId:null,generation:input.generation??1,leaseExpiresAt:now+leaseMs,createdAt:now,updatedAt:now};if(!await writeBackgroundCoderReservations(directory,[...reservations,reservation]))return{ok:!1,reason:"uncertain",detail:"durable reservation claim could not be persisted"};return{ok:!0,reservation,activeCount:activeOwnerKeys.size+1}})}catch(error49){return{ok:!1,reason:"uncertain",detail:`background coder reservation lock failed: ${error49 instanceof Error?error49.message:String(error49)}`}}}async function bindBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||!input.correlationId||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId||input.reservationId!==buildBackgroundCoderReservationId(input)||!isValidReservationGeneration(input.generation))return null;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT2,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return null;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return null;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID)return null;if(current.state==="bound"){if(current.correlationId!==input.correlationId)return null;let now2=input.now??Date.now(),leaseMs2=clampReservationLeaseMs(input.leaseMs),next2={...current,leaseExpiresAt:now2+leaseMs2,updatedAt:now2},reservations2=[...scan.reservations];return reservations2[index]=next2,await writeBackgroundCoderReservations(directory,reservations2)?next2:current}let currentGeneration=current.generation??1;if(input.generation!==void 0&&input.generation<currentGeneration)return null;let now=input.now??Date.now(),leaseMs=clampReservationLeaseMs(input.leaseMs),next={...current,state:"bound",correlationId:input.correlationId,...input.generation!==void 0||current.generation===void 0?{generation:input.generation??currentGeneration}:{},leaseExpiresAt:now+leaseMs,updatedAt:now},reservations=[...scan.reservations];return reservations[index]=next,await writeBackgroundCoderReservations(directory,reservations)?next:null})}catch{return null}}async function releaseBackgroundCoderReservation(directory,input){if(!validateReservationIdentity(input)||!input.reservationId||input.reservationId!==buildBackgroundCoderReservationId(input)||input.correlationId!==null&&(input.correlationId.length===0||input.correlationId.length>256||input.correlationId.trim()!==input.correlationId)||!isValidReservationGeneration(input.generation))return!1;try{return await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT2,RESERVATION_LOCK_TASK,async()=>{let scan=scanBackgroundCoderReservationsForAdmission(directory);if(scan.status==="uncertain")return!1;let index=scan.reservations.findIndex((reservation)=>reservation.reservationId===input.reservationId);if(index<0)return!1;let current=scan.reservations[index];if(current.parentSessionId!==input.parentSessionId||current.planTaskId!==input.planTaskId||current.callID!==input.callID||current.correlationId!==input.correlationId)return!1;if(input.generation!==void 0&&current.generation!==void 0&&input.generation!==current.generation)return warn(`[background] refusing reservation release: terminal generation ${input.generation} does not match owned generation ${current.generation} for ${input.reservationId}`),!1;if(input.reason==="consumed"){if(current.state!=="bound"||!current.correlationId)return!1;let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain")return!1;let primary=ownerScan.primaryByCorrelation.get(current.correlationId);if(!primary||primary.status!=="consumed"||!exactReservationRecordMatch(current,primary))return!1}let reservations=scan.reservations.filter((_,reservationIndex)=>reservationIndex!==index);return writeBackgroundCoderReservations(directory,reservations)})}catch{return!1}}async function reconcileLegacyCoderSettlements(directory,maxRecords,onReconciled,onAdvisoryReplaced){let reconciler=onReconciled??getLegacyCoderSettlementReconciler(directory),candidates=readDelegations(directory).filter((record2)=>record2.normalizedAgent==="coder"&&Boolean(record2.legacyCoderSettlementTransfer)&&Boolean(record2.terminalResult)).slice(0,maxRecords);if(candidates.length===0)return 0;let{transferCoderSettlementToBackground:transferCoderSettlementToBackground2}=await Promise.resolve().then(() => (init_coder_settlement(),exports_coder_settlement)),transferred=0;for(let record2 of candidates)try{let outcome=await transferCoderSettlementToBackground2({directory,taskId:record2.legacyCoderSettlementTransfer.taskId,transitionId:record2.legacyCoderSettlementTransfer.transitionId});if((outcome==="transferred"||outcome==="already-terminal"||outcome==="missing")&&reconciler){if(await reconciler(record2))await clearLegacyCoderSettlementTransferPending(directory,record2.correlationId)}if(outcome==="transferred")transferred+=1}catch(error49){let code=legacySettlementErrorCode(error49);if(!RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES.has(code??"")){let advisory=record2.advisoryInbox,manualMessage=`[BACKGROUND COMPLETION ${record2.terminalResult?.eventId??record2.correlationId}] coder task ${record2.evidenceTaskId??record2.planTaskId??"unknown"} legacy coder settlement requires manual recovery; run /swarm recover for this task (or /swarm reset-session).`,advisoryRecorded=!1;if(advisory?.state==="pending"){let replaced=await replacePendingBackgroundAdvisory(directory,record2.correlationId,{eventId:advisory.eventId,parentSessionId:advisory.parentSessionId,message:manualMessage});if(advisoryRecorded=replaced!==null,replaced)try{await onAdvisoryReplaced?.(record2,replaced)}catch(callbackError){warn(`[background] legacy coder settlement advisory replacement notification failed for ${record2.correlationId}: ${callbackError instanceof Error?callbackError.message:String(callbackError)}`)}}else if(record2.terminalResult)advisoryRecorded=await putPendingBackgroundAdvisory(directory,record2.correlationId,{eventId:record2.terminalResult.eventId,parentSessionId:record2.parentSessionId,message:manualMessage})!==null;if(advisoryRecorded)await clearLegacyCoderSettlementTransferPending(directory,record2.correlationId);warn(`[background] legacy coder settlement reconciliation requires manual recovery for ${record2.correlationId}: ${code??"unknown transfer failure"}`);continue}warn(`[background] legacy coder settlement reconciliation deferred for ${record2.correlationId}: ${error49 instanceof Error?error49.message:String(error49)}`)}return transferred}function legacySettlementErrorCode(error49){if(error49&&typeof error49==="object"&&"code"in error49&&typeof error49.code==="string")return error49.code??null;let detail=error49 instanceof Error?error49.message:String(error49);return/^([A-Z][A-Z0-9_]*)(?::|$)/.exec(detail.trim())?.[1]??null}async function maintainBackgroundDelegations(directory,options={}){let now=options.now??Date.now(),staleTimeoutMs=options.staleTimeoutMs??DEFAULT_STALE_DELEGATION_TIMEOUT_MS,maxRecords=options.maxRecords??DEFAULT_MAINTENANCE_BATCH,lockTimeoutMs=options.lockTimeoutMs??DEFAULT_MAINTENANCE_LOCK_TIMEOUT_MS,reason=options.reason??"manual",result={status:"ok",sweptStale:0,released:[],renewed:[],retained:[],examinedReservations:0},facts=[],emitObservation=(status,failureReason)=>{return appendDelegationMaintenanceObservation(directory,{at:now,status,reason:failureReason,summary:status==="ok"?{sweptStale:result.sweptStale,released:result.released.length,renewed:result.renewed.length,retained:result.retained.length}:void 0,facts}),{...result,status,...failureReason?{reason:failureReason}:{}}};try{result.sweptStale=await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>sweepStaleLocked(directory,staleTimeoutMs,now,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,{},{maxSweep:maxRecords}),lockTimeoutMs)}catch(error49){if(error49 instanceof EvidenceLockTimeoutError)return facts.push({at:now,kind:"lock-contention",reason:`maintenance point '${reason}' skipped: delegations store lock contended`}),emitObservation("contention",error49.message);return facts.push({at:now,kind:"maintenance-failure",reason:`maintenance point '${reason}' sweep failed: ${error49 instanceof Error?error49.message:String(error49)}`}),emitObservation("failure",error49 instanceof Error?error49.message:String(error49))}try{await withEvidenceLock(directory,BACKGROUND_CODER_RESERVATIONS_FILE,STORE_LOCK_AGENT2,RESERVATION_LOCK_TASK,async()=>{let reservationScan=scanBackgroundCoderReservationsForAdmission(directory);if(reservationScan.status==="uncertain"){result.status="failure",result.reason=reservationScan.reason,facts.push({at:now,kind:"maintenance-failure",reason:`reservation store uncertain: ${reservationScan.reason}`});return}let ownerScan=await scanDurableCoderOwners(directory);if(ownerScan.status==="uncertain"){result.status="failure",result.reason=ownerScan.reason,facts.push({at:now,kind:"maintenance-failure",reason:`owner evidence uncertain; all reservations retained: ${ownerScan.reason}`});return}let batch=reservationScan.reservations.slice(0,maxRecords);result.examinedReservations=batch.length;let next=[],mutated=!1;for(let reservation of batch){let generation=reservation.generation??1,primary=findExactPrimaryReservationOwner(reservation,ownerScan);if(primary&&hasProvenReleasedReservationOwner(primary)){if((primary.generation??1)!==generation){result.retained.push({reservationId:reservation.reservationId,reason:"owner-terminal-older-generation"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`proven-terminal owner is generation ${primary.generation??1}, reservation owns ${generation}`}),next.push(reservation);continue}mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"proven-terminal-owner"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"proven-terminal-owner"});continue}if(reservation.leaseExpiresAt===void 0){result.retained.push({reservationId:reservation.reservationId,reason:"protected-legacy-no-lease"}),facts.push({at:now,kind:"retained-protected-legacy",reservationId:reservation.reservationId,generation,reason:"legacy reservation without leaseExpiresAt"}),next.push(reservation);continue}if(!(reservation.leaseExpiresAt<=now)){next.push(reservation);continue}if(primary){if((primary.generation??1)!==generation){result.retained.push({reservationId:reservation.reservationId,reason:"owner-older-generation"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`owner record is generation ${primary.generation??1}, reservation owns ${generation}`}),next.push(reservation);continue}if(primary.status==="stale"){mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"owner-swept-stale"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"owner record durably stale"});continue}if(isActiveCoderOwner(primary)){mutated=!0,result.renewed.push({reservationId:reservation.reservationId,generation}),facts.push({at:now,kind:"lease-renewed",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"exact owner record still active"}),next.push({...reservation,leaseExpiresAt:now+BACKGROUND_CODER_RESERVATION_LEASE_MS,updatedAt:now});continue}result.retained.push({reservationId:reservation.reservationId,reason:"owner-terminal-unproven"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:`owner status '${primary.status}' does not prove release`}),next.push(reservation);continue}if(reservation.correlationId!==null&&ownerScan.recordsByCorrelation.has(reservation.correlationId)){result.retained.push({reservationId:reservation.reservationId,reason:"owner-identity-mismatch"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,correlationId:reservation.correlationId??void 0,generation,reason:"correlation exists under a different owner identity"}),next.push(reservation);continue}if(now-reservation.createdAt>staleTimeoutMs){mutated=!0,result.released.push({reservationId:reservation.reservationId,generation,reason:"unbound-orphan"}),facts.push({at:now,kind:"release",reservationId:reservation.reservationId,generation,reason:"no durable owner anywhere and pre-launch window exceeded"});continue}result.retained.push({reservationId:reservation.reservationId,reason:"unbound-within-stale-window"}),facts.push({at:now,kind:"retained-ambiguity",reservationId:reservation.reservationId,generation,reason:"no owner record yet; still inside the pre-launch stale window"}),next.push(reservation)}if(next.push(...reservationScan.reservations.slice(maxRecords)),mutated){if(!await writeBackgroundCoderReservations(directory,next))result.status="failure",result.reason="reservation reconciliation could not be persisted",facts.push({at:now,kind:"maintenance-failure",reason:"reservation store write failed during reconciliation"})}},lockTimeoutMs)}catch(error49){if(error49 instanceof EvidenceLockTimeoutError)return facts.push({at:now,kind:"lock-contention",reason:`maintenance point '${reason}' skipped: reservation store lock contended`}),emitObservation("contention",error49.message);return facts.push({at:now,kind:"maintenance-failure",reason:`maintenance point '${reason}' reconciliation failed: ${error49 instanceof Error?error49.message:String(error49)}`}),emitObservation("failure",error49 instanceof Error?error49.message:String(error49))}if(!options.skipLegacyCoderSettlementReconciliation)try{await reconcileLegacyCoderSettlements(directory,maxRecords,options.onLegacyCoderSettlementReconciled??getLegacyCoderSettlementReconciler(directory),options.onLegacyCoderSettlementAdvisoryReplaced)}catch(error49){warn(`[background] legacy coder settlement reconciliation pass failed: ${error49 instanceof Error?error49.message:String(error49)}`)}if(result.status==="failure")return emitObservation("failure",result.reason);return emitObservation("ok")}var BACKGROUND_DELEGATIONS_FILE="background-delegations.jsonl",BACKGROUND_DELEGATION_FALLBACK_DIR="background-delegation-fallback",BACKGROUND_CODER_RESERVATIONS_FILE="background-coder-reservations.json",BACKGROUND_DELEGATIONS_CHECKPOINT_FILE="background-delegations.checkpoint.json",BACKGROUND_DELEGATIONS_MANIFEST_FILE="background-delegations.manifest.json",MAX_LIVE_BACKGROUND_FALLBACKS=256,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS=256,MAX_BACKGROUND_OBSERVED_FILES=5000,MAX_BACKGROUND_ADVISORY_CHARS=4000,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER="legacy coder settlement transfer is pending",MAX_BACKGROUND_DELEGATION_GENERATION=1e6,DELEGATION_COORDINATION_NAMESPACE="background.pending-delegation",RESERVATION_COORDINATION_NAMESPACE="background.coder-reservation",RESERVATION_LEASE_NAMESPACE="background.coder-reservation.lease",MAX_RECOVERY_FALLBACK_BYTES=1048576,MAX_TRACKED_LENIENT_LEDGER_SIGNALS=32,LENIENT_LEDGER_SIGNAL_SOURCE="lenient-read",DELEGATION_COMPACTION_LOW_WATER_BYTES=262144,DELEGATION_COMPACTION_HIGH_WATER_BYTES=1048576,MAX_CHECKPOINT_BYTES=2097152,CHECKPOINT_SELECTION_RESERVE_BYTES=65536,MAX_CHECKPOINT_RECORDS=2048,MAX_COORDINATION_DELEGATION_ROWS,MAX_COORDINATION_TERMINAL_ROWS,TOMBSTONE_MIN_AGE_MS=259200000,STORE_LOCK_AGENT2="background",STORE_LOCK_TASK2="background-delegations",FALLBACK_LOCK_TASK="background-delegation-fallback",RESERVATION_LOCK_TASK="background-coder-reservations",ADVISORY_PREPARE_LEASE_MS=30000,INGESTION_CLAIM_LEASE_MS=30000,BACKGROUND_INGESTION_LEASE_MS=30000,BACKGROUND_CODER_RESERVATION_LEASE_MS=900000,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS=3600000,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS=60000,DEFAULT_STALE_DELEGATION_TIMEOUT_MS=1800000,DEFAULT_SWEEPABLE_DELEGATION_STATUSES,WorkflowLaneRecoverySchema,ResultSchema,WorkspaceSchema,TaskChangeContextSchema,WorktreeDescriptorSchema,TerminalResultSchema,NormalizedObservedFileSchema,SettlementProvenanceSchema,SettlementOutcomeSchema,CoderSettlementSchema,AdvisoryPreparationSchema,AdvisoryInboxSchema,DelegationIngestionSchema,BackgroundCoderReservationSchema,BackgroundCoderReservationStoreSchema,PromptSchema,RecordSchema2,FallbackArtifactSchema,SHA256_HEX,CheckpointSchema2,ManifestSchema,WRITER_ID,_checkpointInternals,CHECKPOINT_REBIND_HINT="remove .swarm/background-delegations.manifest.json (manifest only) after verifying no in-flight background delegations; recovery then falls back to the full-ledger read. Only if you also want to discard pre-cut closed summaries and audit history — which for a compacted (rolled) ledger exist ONLY in .swarm/background-delegations.checkpoint.json — remove the checkpoint too or use the full reset below",CHECKPOINT_RESET_HINT="the rolled tail no longer carries pre-checkpoint state: stop swarm processes, verify no in-flight background delegations, and remove .swarm/background-delegations.manifest.json, .swarm/background-delegations.checkpoint.json, and .swarm/background-delegations.jsonl to reset the store (or restore them from backup)",lenientLedgerSignalByRoot,lenientLedgerSignalOrder,MAX_LEGACY_CODER_SETTLEMENT_RECONCILERS=32,RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES,legacyCoderSettlementReconcilers,legacyCoderSettlementReconcilerOrder,_internals85,_staleSweepObserver=null,MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES=2097152,DEFAULT_MAINTENANCE_LOCK_TIMEOUT_MS=5000,DEFAULT_MAINTENANCE_BATCH=256;var init_pending_delegations=__esm(()=>{init_zod();init_db();init_lock();init_utils2();init_bun_compat();init_canonical_root();init_logger();init_delegation_health();init_pr_review_collection_receipt();init_pr_review_contract();init_delegation_health();init_delegation_health();MAX_COORDINATION_DELEGATION_ROWS=MAX_CHECKPOINT_RECORDS*2,MAX_COORDINATION_TERMINAL_ROWS=MAX_CHECKPOINT_RECORDS;DEFAULT_SWEEPABLE_DELEGATION_STATUSES=new Set(["pending","running","ingestion_error"]),WorkflowLaneRecoverySchema=exports_external.object({workflowLane:exports_external.string(),kind:exports_external.enum(["legacy-verdict-row-recovery","parser-normalization","parser-row-recovery","truncated-preview-durable-artifact","transcript-incomplete-terminal-candidate","clean-attestation-salvaged"]),reason:exports_external.string()}).strict(),ResultSchema=exports_external.object({text:exports_external.string().optional(),error:exports_external.string().optional(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string(),outputRef:exports_external.string().optional(),outputPreviewChars:exports_external.number().optional(),outputDegraded:exports_external.boolean().optional(),outputArtifactError:exports_external.string().optional(),transcriptIncomplete:exports_external.boolean().optional(),messageCount:exports_external.number().optional(),prReviewResultReceipt:PrReviewResultReceiptSchema.optional(),workflowLaneFailureClass:exports_external.enum(["contract","resource","deadline"]).optional(),terminalErrorClass:exports_external.object({kind:exports_external.enum(["provider","aborted","output_length","unknown"]),category:exports_external.string().min(1).max(128),statusCode:exports_external.number().int().optional(),hostRetryable:exports_external.boolean().optional()}).strict().optional(),salvagedWorkflowLanes:exports_external.array(exports_external.string()).optional(),salvagedWorkflowLaneRecoveries:exports_external.array(WorkflowLaneRecoverySchema).optional()}).strict(),WorkspaceSchema=exports_external.object({directory:exports_external.string(),gitHead:exports_external.string().nullable(),dirtyHash:exports_external.string().nullable(),changedFiles:exports_external.array(exports_external.string()).nullable().optional(),prHeadSha:exports_external.string().nullable(),scope:exports_external.string().nullable()}).strict(),TaskChangeContextSchema=exports_external.object({declaredFiles:exports_external.array(exports_external.string()).nullable(),baseline:WorkspaceSchema,workflowGeneration:exports_external.number().int().nonnegative().optional()}).strict(),WorktreeDescriptorSchema=exports_external.object({callID:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),taskId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),worktreePath:exports_external.string().min(1).max(4096),branchName:exports_external.string().min(1).max(1024),worktreeId:exports_external.string().min(1).max(256),worktreeSessionId:exports_external.string().min(1).max(256),mergeStrategy:exports_external.enum(["merge","rebase","cherry-pick"]),laneIndex:exports_external.number().int().nonnegative().max(255),worktreeDir:exports_external.string().min(1).max(4096).nullable(),reservationId:exports_external.string().min(1).max(512).optional(),generation:exports_external.number().int().min(1).optional(),provisioningOwner:exports_external.object({reservationId:exports_external.string().min(1).max(512),generation:exports_external.number().int().min(1),branchName:exports_external.string().min(1).max(1024)}).strict().optional()}).strict(),TerminalResultSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),status:exports_external.enum(["completed","error","cancelled","rejected"]),recordedAt:exports_external.number().int().nonnegative(),result:ResultSchema}).strict(),NormalizedObservedFileSchema=exports_external.string().min(1).max(4096).refine((value)=>normalizeObservedFile(value)===value),SettlementProvenanceSchema=exports_external.object({correlationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),callID:exports_external.string().max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),baseline:WorkspaceSchema,worktree:WorktreeDescriptorSchema.nullable()}).strict(),SettlementOutcomeSchema=exports_external.object({kind:exports_external.enum(["shared-root","standard-worktree"]),result:exports_external.enum(["ready","merged","unchanged","partial","failed"]),reason:exports_external.string().min(1).max(2000).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),targetHeadAfterMerge:exports_external.string().min(1).max(256).nullable().optional()}).strict(),CoderSettlementSchema=exports_external.object({state:exports_external.enum(["pending","settling","settled","preserved"]),provenance:SettlementProvenanceSchema,operationId:exports_external.string().min(1).max(256).optional(),sourceHeadAfterCommit:exports_external.string().min(1).max(256).nullable().optional(),targetHeadBeforeMerge:exports_external.string().min(1).max(256).nullable().optional(),observedFiles:exports_external.array(NormalizedObservedFileSchema).max(MAX_BACKGROUND_OBSERVED_FILES).nullable(),outcome:SettlementOutcomeSchema.optional(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state!=="pending"&&!value.operationId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"settling, settled, and preserved states require operationId"});if((value.state==="settled"||value.state==="preserved")&&!value.outcome)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"terminal settlement state requires outcome"})}),AdvisoryPreparationSchema=exports_external.object({id:exports_external.string().min(1).max(256),preparedAt:exports_external.number().int().nonnegative(),leaseExpiresAt:exports_external.number().int().nonnegative()}).strict(),AdvisoryInboxSchema=exports_external.object({eventId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),state:exports_external.enum(["pending","delivered"]),message:exports_external.string().min(1).max(MAX_BACKGROUND_ADVISORY_CHARS),createdAt:exports_external.number().int().nonnegative(),preparation:AdvisoryPreparationSchema.optional(),deliveredAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="delivered"&&value.deliveredAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory requires deliveredAt"});if(value.state==="delivered"&&value.preparation!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"delivered advisory cannot retain a preparation lease"})}),DelegationIngestionSchema=exports_external.object({state:exports_external.enum(["claimed","retryable","consumed"]),attempt:exports_external.number().int().positive(),updatedAt:exports_external.number().int().nonnegative(),claimToken:exports_external.string().min(1).max(256),leaseExpiresAt:exports_external.number().int().nonnegative().optional()}).strict().superRefine((value,context)=>{if(value.state==="claimed"&&value.leaseExpiresAt===void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"claimed ingestion requires a lease expiry"});if(value.state!=="claimed"&&value.leaseExpiresAt!==void 0)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"completed ingestion cannot retain a claim lease"})}),BackgroundCoderReservationSchema=exports_external.object({reservationId:exports_external.string().min(1).max(256),parentSessionId:exports_external.string().min(1).max(256),planTaskId:exports_external.string().min(1).max(256).nullable(),callID:exports_external.string().min(1).max(256),state:exports_external.enum(["reserved","bound"]),correlationId:exports_external.string().min(1).max(256).nullable(),generation:exports_external.number().int().min(1).max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),leaseExpiresAt:exports_external.number().int().nonnegative().optional(),createdAt:exports_external.number().int().nonnegative(),updatedAt:exports_external.number().int().nonnegative()}).strict().superRefine((value,context)=>{if(value.state==="reserved"&&value.correlationId!==null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"unbound reservation cannot have a correlationId"});if(value.state==="bound"&&value.correlationId===null)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"bound reservation requires a correlationId"})}),BackgroundCoderReservationStoreSchema=exports_external.object({schemaVersion:exports_external.literal(1),reservations:exports_external.array(BackgroundCoderReservationSchema).max(MAX_LIVE_BACKGROUND_CODER_RESERVATIONS)}).strict().superRefine((value,context)=>{let ids=new Set;for(let reservation of value.reservations){if(ids.has(reservation.reservationId)){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"duplicate reservationId"});return}if(reservation.reservationId!==buildBackgroundCoderReservationId({parentSessionId:reservation.parentSessionId,planTaskId:reservation.planTaskId,callID:reservation.callID})){context.addIssue({code:exports_external.ZodIssueCode.custom,message:"reservationId does not match owner identity"});return}ids.add(reservation.reservationId)}}),PromptSchema=exports_external.object({text:exports_external.string(),chars:exports_external.number(),truncated:exports_external.boolean(),digest:exports_external.string()}).strict(),RecordSchema2=exports_external.object({schemaVersion:exports_external.union([exports_external.literal(1),exports_external.literal(2),exports_external.literal(3),exports_external.literal(4)]),correlationId:exports_external.string().min(1),jobId:exports_external.string().nullable(),subagentSessionId:exports_external.string().min(1),parentSessionId:exports_external.string().min(1),callID:exports_external.string(),normalizedAgent:exports_external.string(),swarmPrefixedAgent:exports_external.string(),planTaskId:exports_external.string().nullable(),evidenceTaskId:exports_external.string().nullable(),status:exports_external.enum(["pending","running","ingestion_error","rejected","completed","error","cancelled","stale","consumed"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),batchId:exports_external.string().optional(),laneId:exports_external.string().optional(),mode:exports_external.string().optional(),workflowLane:exports_external.string().optional(),ownedWorkflowLanes:exports_external.array(exports_external.string().min(1).max(120)).min(1).max(11).optional(),prReviewLegacyTranscriptCompatibility:exports_external.boolean().optional(),promptHash:exports_external.string().optional(),workspace:WorkspaceSchema.optional(),taskChangeContext:TaskChangeContextSchema.optional(),workflowGeneration:exports_external.number().int().nonnegative().optional(),worktree:WorktreeDescriptorSchema.optional(),coderReservationId:exports_external.string().min(1).max(256).optional(),prompt:PromptSchema.optional(),generation:exports_external.number().int().positive().max(MAX_BACKGROUND_DELEGATION_GENERATION).optional(),terminalResult:TerminalResultSchema.optional(),coderSettlement:CoderSettlementSchema.optional(),advisoryInbox:AdvisoryInboxSchema.optional(),legacyCoderSettlementTransfer:exports_external.object({taskId:exports_external.string().min(1).max(256),transitionId:exports_external.string().min(1).max(256),updatedAt:exports_external.number().nonnegative()}).strict().optional(),ingestion:DelegationIngestionSchema.optional(),result:ResultSchema.optional(),completedAt:exports_external.number().optional()}).strict().superRefine((value,context)=>{if(value.mode?.startsWith("swarm-pr-review:")&&value.correlationId!==value.subagentSessionId)context.addIssue({code:exports_external.ZodIssueCode.custom,message:"PR-review delegation identity requires correlationId to equal subagentSessionId"})}),FallbackArtifactSchema=exports_external.object({schemaVersion:exports_external.literal(1),correlationId:exports_external.string().min(1).max(256),createdAt:exports_external.number().int().nonnegative(),record:RecordSchema2}).strict().superRefine((value,context)=>{if(value.record.correlationId!==value.correlationId||value.record.subagentSessionId!==value.correlationId||value.record.status!=="pending")context.addIssue({code:exports_external.ZodIssueCode.custom,message:"fallback identity/status does not match its pending record"})});SHA256_HEX=/^[0-9a-f]{64}$/,CheckpointSchema2=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),createdAt:exports_external.number().int().nonnegative(),cutLedgerBytes:exports_external.number().int().nonnegative(),cutLedgerDigest:exports_external.string().regex(SHA256_HEX),records:exports_external.array(RecordSchema2).max(MAX_CHECKPOINT_RECORDS),closed:exports_external.array(RecordSchema2),audit:DelegationCheckpointAuditSchema,payloadChecksum:exports_external.string().regex(SHA256_HEX)}).strict(),ManifestSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),checkpointChecksum:exports_external.string().regex(SHA256_HEX),writerId:exports_external.string().min(1).max(128),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative()}).strict(),WRITER_ID=`w-${process.pid}-${Math.random().toString(36).slice(2,10)}`,_checkpointInternals={renameWithRetry:(from,to)=>{let lastError;for(let attempt=0;attempt<5;attempt++)try{_checkpointInternals.renameOnce(from,to);return}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")throw err;_checkpointInternals.syncSleep(15)}throw lastError},renameOnce:(from,to)=>{fs58.renameSync(from,to)},syncSleep:(ms)=>{try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}};lenientLedgerSignalByRoot=new Map,lenientLedgerSignalOrder=[];RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),legacyCoderSettlementReconcilers=new Map,legacyCoderSettlementReconcilerOrder=[];_internals85={getLegacyCoderSettlementReconciler,readFallbackDirectory,getLegacyCoderSettlementReconcilerOrder:()=>[...legacyCoderSettlementReconcilerOrder],resetLegacyCoderSettlementReconcilers:()=>{legacyCoderSettlementReconcilers.clear(),legacyCoderSettlementReconcilerOrder.length=0},reservationCoordinationRowLimit:MAX_COORDINATION_STATE_LIST_ROWS,writeBackgroundCoderReservations}});import{createHash as createHash43}from"node:crypto";function rawTriggerIds(input){if(!Array.isArray(input))return null;let ids=[];for(let row of input){if(typeof row!=="object"||row===null)return null;let triggerId=row.trigger_id;if(typeof triggerId!=="string"||!triggerId.trim())return null;ids.push(triggerId.trim())}return ids}function assertExactTriggerIdSet(input){let ids=rawTriggerIds(input);if(!ids)return;let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let id of ids){if(seen.has(id))duplicate.add(id);seen.add(id)}if(duplicate.size>0)throw Error(`duplicate trigger IDs: ${[...duplicate].join(", ")}`);let unknown2=[...seen].filter((id)=>!expected.has(id));if(unknown2.length>0)throw Error(`unknown trigger IDs: ${unknown2.join(", ")}. trigger_id must be one of the 11 mandatory micro-lane IDs: ${[...expected].join(", ")}. Base-lane IDs and mode strings (e.g. swarm-pr-review:base) are NOT trigger IDs.`);let missing=[...expected].filter((id)=>!seen.has(id));if(missing.length>0)throw Error(`missing trigger IDs: ${missing.join(", ")}`)}function assertMatchedRowsHaveProvenance(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;let value=row;if(value.result!=="MATCHED")continue;if(typeof value.source_batch_id!=="string"||!value.source_batch_id.trim()||typeof value.source_lane_id!=="string"||!value.source_lane_id.trim())throw Error(`MATCHED rows require source_batch_id and source_lane_id: ${String(value.trigger_id??"(missing trigger_id)")}`)}}function assertNoLegacyNoMatchResult(input){if(!Array.isArray(input))return;for(let row of input){if(typeof row!=="object"||row===null)continue;if(row.result==="NO-MATCH")throw Error("NO-MATCH is not a valid PR_REVIEW trigger result; use MATCHED or NOT_TRIGGERED with concrete evidence")}}function exactTriggerRows(rows){let expected=new Set(PR_REVIEW_REQUIRED_TRIGGER_IDS),seen=new Set,duplicate=new Set;for(let row of rows){if(seen.has(row.trigger_id))duplicate.add(row.trigger_id);seen.add(row.trigger_id)}let unknown2=[...seen].filter((id)=>!expected.has(id)),missing=[...expected].filter((id)=>!seen.has(id));if(duplicate.size>0||unknown2.length>0||missing.length>0)throw Error(`PR_REVIEW trigger ledger must be exact; missing: ${missing.join(", ")||"(none)"}; duplicate: ${[...duplicate].join(", ")||"(none)"}; unknown: ${unknown2.join(", ")||"(none)"}`);let byId=new Map(rows.map((row)=>[row.trigger_id,row]));return PR_REVIEW_REQUIRED_TRIGGER_IDS.map((id)=>{let row=byId.get(id);if(!row)throw Error(`missing trigger row: ${id}`);return row})}function summarizeTriggerRows(rows){let orderedRows=exactTriggerRows(rows);if(orderedRows.find((row)=>row.trigger_id==="unclassified-risk")?.result!=="MATCHED")throw Error("PR_REVIEW trigger ledger requires unclassified-risk to remain MATCHED as the fallback family");return{rows:orderedRows,matchedIds:orderedRows.filter((row)=>row.result==="MATCHED").map((row)=>row.trigger_id),notTriggeredIds:orderedRows.filter((row)=>row.result==="NOT_TRIGGERED").map((row)=>row.trigger_id)}}function parseRows(input,schema,label){let parsed=exports_external.array(schema).safeParse(input);if(!parsed.success)throw Error(`${label}: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function validatePrReviewInlineTriggerLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),summarizeTriggerRows(parseRows(input,PrReviewInlineTriggerRowSchema,"Invalid trigger ledger"))}function validatePrReviewPersistedInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewPersistedInputRowSchema,"Invalid persisted trigger ledger"))}function validatePrReviewWriterInputLedger(input){return assertExactTriggerIdSet(input),assertNoLegacyNoMatchResult(input),assertMatchedRowsHaveProvenance(input),summarizeTriggerRows(parseRows(input,PrReviewWriterInputRowSchema,"Invalid final-writer trigger ledger"))}function assertCanonicalDefinitionFields(rows){let definitions=new Map(PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>[definition.id,definition]));for(let row of rows){let definition=definitions.get(row.trigger_id);if(!definition||row.scope!==definition.scope||row.trigger_row!==definition.trigger_row||row.micro_lane!==definition.micro_lane)throw Error(`PR_REVIEW trigger definition drift for ${row.trigger_id}: scope, trigger_row, and micro_lane must match the canonical definition`)}}function dispatchedMicroLaneCount(rows){return new Set(rows.filter((row)=>row.result==="MATCHED").map((row)=>`${row.source_batch_id}\x00${row.source_lane_id}`)).size}function buildPrReviewTriggerReceiptV2(input){let envelope=ReceiptEnvelopeSchema.parse(input),validated=validatePrReviewPersistedInputLedger(input.rows),dispatchedCount=dispatchedMicroLaneCount(validated.rows);if(envelope.dispatched_micro_lane_count!==dispatchedCount)throw Error(`PR_REVIEW trigger receipt dispatched_micro_lane_count is inconsistent: expected ${dispatchedCount}`);let rows=validated.rows.map((row)=>{let definition=PR_REVIEW_TRIGGER_DEFINITIONS.find((candidate)=>candidate.id===row.trigger_id);if(!definition)throw Error(`unknown trigger definition: ${row.trigger_id}`);return{trigger_id:row.trigger_id,scope:definition.scope,trigger_row:definition.trigger_row,micro_lane:definition.micro_lane,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}}});return V2ReceiptSchema.parse({...envelope,schema_version:2,trigger_count:rows.length,matched_count:validated.matchedIds.length,not_triggered_count:validated.notTriggeredIds.length,no_match_count:0,rows,coverage_degradations:input.coverage_degradations??[],...input.base_verification?{base_verification:input.base_verification}:{}})}function prReviewTriggerLedgerDigest(rows){let canonical=rows.map((row)=>[row.trigger_id,row.result,row.evidence]);return createHash43("sha256").update(JSON.stringify(canonical)).digest("hex")}function parsedReceipt(schemaVersion,rows,coverageDegradations=[],baseVerification){return{schemaVersion,rows,matchedRows:rows.filter((row)=>row.result==="MATCHED"),notTriggeredRows:rows.filter((row)=>row.result==="NOT_TRIGGERED"),coverageDegradations,...baseVerification?{baseVerification}:{}}}function parsePrReviewTriggerReceipt(input){if(typeof input!=="object"||input===null)throw Error("PR_REVIEW trigger receipt must be an object");let schemaVersion=input.schema_version;if(schemaVersion===2){let receipt=V2ReceiptSchema.parse(input);assertCanonicalDefinitionFields(receipt.rows);let normalizedRows=receipt.rows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,...row.result==="MATCHED"?{source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id}:{}})),validated2=validatePrReviewPersistedInputLedger(normalizedRows),counts={trigger_count:validated2.rows.length,matched_count:validated2.matchedIds.length,not_triggered_count:validated2.notTriggeredIds.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated2.rows)};for(let[field,expected]of Object.entries(counts))if(receipt[field]!==expected)throw Error(`PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`);return parsedReceipt(2,validated2.rows,receipt.coverage_degradations,receipt.base_verification)}if(schemaVersion!==void 0&&schemaVersion!==1)throw Error(`Unsupported PR_REVIEW trigger schema_version: ${schemaVersion}`);let legacyEnvelope=schemaVersion===1?V1ReceiptSchema.parse(input):UnversionedRowOnlyReceiptSchema.parse(input),rowsInput=legacyEnvelope.rows,parsedLegacyRows=parseRows(rowsInput,LegacyRowSchema,"Invalid legacy trigger ledger; all rows must be MATCHED with complete source provenance");assertCanonicalDefinitionFields(parsedLegacyRows.filter((row)=>("scope"in row)));let legacyRows=parsedLegacyRows.map((row)=>({trigger_id:row.trigger_id,result:row.result,evidence:row.evidence,source_batch_id:row.source_batch_id,source_lane_id:row.source_lane_id})),validated=summarizeTriggerRows(legacyRows);if(schemaVersion===1){let receipt=legacyEnvelope,countFields={trigger_count:validated.rows.length,matched_count:validated.rows.length,no_match_count:0,dispatched_micro_lane_count:dispatchedMicroLaneCount(validated.rows)};for(let[field,expected]of Object.entries(countFields))if(receipt[field]!==expected)throw Error(`Historical PR_REVIEW trigger receipt ${field} is inconsistent: expected ${expected}`)}return parsedReceipt(schemaVersion===1?1:0,validated.rows)}var PR_REVIEW_TRIGGER_DEFINITIONS,PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES=2097152,TriggerIdSchema,TriggerEvidenceSchema,PrReviewInlineTriggerRowSchema,PrReviewPersistedInputRowSchema,PrReviewWriterInputRowSchema,TriggerDefinitionFieldShape,V2MatchedRowSchema,V2NotTriggeredRowSchema,V2RowSchema,TriggerCoverageDegradationSchema,ReceiptEnvelopeSchema,V2ReceiptSchema,LegacyRowFieldShape,LegacyBasicRowSchema,LegacyFullRowSchema,LegacyRowSchema,V1ReceiptSchema,UnversionedRowOnlyReceiptSchema;var init_pr_review_trigger_contract=__esm(()=>{init_zod();PR_REVIEW_TRIGGER_DEFINITIONS=[{id:"auth-identity-secrets",scope:"universal",trigger_row:"authentication, authorization, identity, sessions, permissions, secrets, cryptography",micro_lane:"Identity and secret boundaries"},{id:"untrusted-input-boundaries",scope:"universal",trigger_row:"parsing, serialization, queries, templates/rendering, file or network input/output",micro_lane:"Untrusted input and sink analysis"},{id:"subprocess-platform",scope:"universal",trigger_row:"subprocesses, shell commands, filesystem operations, OS/runtime-specific code",micro_lane:"Subprocess and platform safety"},{id:"concurrency-state",scope:"universal",trigger_row:"queues, caches, retries, transactions, locks, state machines, async coordination",micro_lane:"Concurrency and state transitions"},{id:"dependencies-build-release",scope:"universal",trigger_row:"dependency manifests, lockfiles, installers, build scripts, CI, packaging, deployment",micro_lane:"Dependency and delivery integrity"},{id:"api-schema-migrations",scope:"universal",trigger_row:"public API, wire/schema/config/storage formats, migrations, feature flags",micro_lane:"Compatibility and migration safety"},{id:"test-infrastructure",scope:"universal",trigger_row:"tests, mocks, fixtures, harnesses, coverage, CI matrices",micro_lane:"Test validity and isolation"},{id:"ui-accessibility-i18n",scope:"universal",trigger_row:"user interfaces, interaction flows, rendering, accessibility, localization",micro_lane:"UI and human-interface quality"},{id:"privacy-observability",scope:"universal",trigger_row:"telemetry, logs, analytics, traces, retention, diagnostics",micro_lane:"Privacy and observability safety"},{id:"generated-provenance",scope:"universal",trigger_row:"generated, vendored, binary, model-produced, codegen or checked-in build artifacts",micro_lane:"Generated artifact provenance"},{id:"unclassified-risk",scope:"universal",trigger_row:"any changed artifact or behavior not confidently classified by the rows above",micro_lane:"Unclassified high-risk fallback"}],PR_REVIEW_REQUIRED_TRIGGER_IDS=PR_REVIEW_TRIGGER_DEFINITIONS.map((definition)=>definition.id),TriggerIdSchema=exports_external.enum(PR_REVIEW_REQUIRED_TRIGGER_IDS,{error:"unknown PR_REVIEW trigger_id"}),TriggerEvidenceSchema=exports_external.string().trim().min(1).max(4000),PrReviewInlineTriggerRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewPersistedInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict()]),PrReviewWriterInputRowSchema=exports_external.discriminatedUnion("result",[exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema.optional(),source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),exports_external.object({trigger_id:TriggerIdSchema,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema.optional()}).strict()]);TriggerDefinitionFieldShape={scope:exports_external.literal("universal"),trigger_row:exports_external.string().trim().min(1),micro_lane:exports_external.string().trim().min(1)},V2MatchedRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),V2NotTriggeredRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("NOT_TRIGGERED"),evidence:TriggerEvidenceSchema}).strict(),V2RowSchema=exports_external.union([V2MatchedRowSchema,V2NotTriggeredRowSchema]),TriggerCoverageDegradationSchema=exports_external.object({trigger_id:TriggerIdSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1),reason:exports_external.string().trim().min(1)}).strict(),ReceiptEnvelopeSchema=exports_external.object({run_id:exports_external.string().regex(/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/),pr_head_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),base_ref:exports_external.string().trim().regex(/^(?!-)[A-Za-z0-9][A-Za-z0-9._/-]{0,255}$/),base_sha:exports_external.string().trim().regex(/^[0-9a-f]{6,64}$/i),evaluated_at:exports_external.string().datetime(),dispatched_micro_lane_count:exports_external.number().int().min(1)}),V2ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(2),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),not_triggered_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(V2RowSchema),coverage_degradations:exports_external.array(TriggerCoverageDegradationSchema).default([]),base_verification:exports_external.enum(["live","bound_fallback"]).optional()}).strict();LegacyRowFieldShape={trigger_id:TriggerIdSchema,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)},LegacyBasicRowSchema=exports_external.object(LegacyRowFieldShape).strict(),LegacyFullRowSchema=exports_external.object({trigger_id:TriggerIdSchema,...TriggerDefinitionFieldShape,result:exports_external.literal("MATCHED"),evidence:TriggerEvidenceSchema,source_batch_id:exports_external.string().trim().min(1),source_lane_id:exports_external.string().trim().min(1)}).strict(),LegacyRowSchema=exports_external.union([LegacyBasicRowSchema,LegacyFullRowSchema]),V1ReceiptSchema=ReceiptEnvelopeSchema.extend({schema_version:exports_external.literal(1),trigger_count:exports_external.number().int().min(0),matched_count:exports_external.number().int().min(0),no_match_count:exports_external.number().int().min(0),rows:exports_external.array(LegacyRowSchema)}).strict(),UnversionedRowOnlyReceiptSchema=exports_external.object({rows:exports_external.array(exports_external.unknown())}).strict()});import*as fs59 from"node:fs";import*as path93 from"node:path";function decodeCompleteUtf8Prefix(bytes){let fatalDecoder=new TextDecoder("utf-8",{fatal:!0});try{return fatalDecoder.decode(bytes)}catch{for(let trim=1;trim<=3&&trim<=bytes.byteLength;trim+=1)try{return fatalDecoder.decode(bytes.subarray(0,bytes.byteLength-trim))}catch{}return new TextDecoder().decode(bytes).replace(/\uFFFD+$/u,"")}}function isExecutableFile(candidate){try{return fs59.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path93.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path93.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path93.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path93.join(dir,`${rawName}${ext}`);if(isExecutableFile(candidate))return candidate}}return null}function clampTimeoutMs(timeoutMs){if(!Number.isFinite(timeoutMs))return MAX_RUNNER_TIMEOUT_MS;return Math.min(Math.max(1,Math.floor(timeoutMs)),MAX_RUNNER_TIMEOUT_MS)}function addTimeoutMs(baseMs,deltaMs){if(baseMs>=MAX_TIMEOUT_MS2)return MAX_TIMEOUT_MS2;return Math.min(MAX_TIMEOUT_MS2,baseMs+deltaMs)}function computeSpawnTimeoutMs(timeoutMs){let total=clampTimeoutMs(timeoutMs);for(let windowMs of[TERMINATION_GRACE_MS,TERMINATION_FORCE_MS,TERMINATION_CONFIRM_MS,TREE_TERMINATION_CONFIRM_MS,TERMINATION_FALLBACK_BUFFER_MS])total=addTimeoutMs(total,windowMs);return total}function startBoundedStreamRead(stream,maxBytes,onLimitExceeded){let reader=stream.getReader(),lockReleased=!1,cancelPromise,releaseLock=()=>{if(lockReleased)return;lockReleased=!0;try{reader.releaseLock()}catch{}},cancel=async()=>{return cancelPromise??=(async()=>{try{await reader.cancel()}catch{}finally{releaseLock()}})(),cancelPromise};if(maxBytes<=0)return onLimitExceeded?.(),{cancel,promise:(async()=>{return await cancel(),{text:"",truncated:!0}})()};return{promise:(async()=>{let chunks=[],total=0,truncated=!1;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;let remaining=maxBytes-total;if(value.byteLength>remaining){if(remaining>0)chunks.push(value.slice(0,remaining)),total+=remaining;truncated=!0,onLimitExceeded?.(),cancel();break}chunks.push(value),total+=value.byteLength}}finally{releaseLock()}let out=new Uint8Array(total),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return{text:decodeCompleteUtf8Prefix(out),truncated}})(),cancel}}function timeoutKillSignal(platform){return platform==="win32"?"SIGTERM":"SIGKILL"}function reportKillFailure(error49,signal){if(error49?.code==="ESRCH")return;_internals86.warn(`external tool process kill failed for ${signal}`,error49)}function killProcess(proc){let signal=timeoutKillSignal(_internals86.platform());try{proc?.kill(signal)}catch(error49){reportKillFailure(error49,signal)}}function requestTermination(proc,signal){try{if(proc?.killTree)return proc.killTree(signal).then(()=>!0,(error49)=>{return reportKillFailure(error49,signal),!1});else return proc?.kill(signal),Promise.resolve(proc!==void 0)}catch(error49){return reportKillFailure(error49,signal),Promise.resolve(!1)}}async function waitForExitWithin(exitPromise,waitMs){if(waitMs<=0)return Promise.resolve(null);let timeoutHandle;try{return await Promise.race([exitPromise,new Promise((resolve47)=>{timeoutHandle=_internals86.setTimeout(()=>resolve47(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals86.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve47)=>{timeoutHandle=_internals86.setTimeout(()=>resolve47({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals86.clearTimeout(timeoutHandle)}}async function collectBoundedStreams(stdoutRead,stderrRead,proc,treeAlreadyConfirmed=!1){let reads=Promise.all([stdoutRead.promise,stderrRead.promise]),collected=await waitForValueWithin(reads,STREAM_DRAIN_MS);if(!collected.completed){let treeTermination=waitForValueWithin(requestTermination(proc,"SIGKILL"),TREE_TERMINATION_CONFIRM_MS);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]),collected=await waitForValueWithin(reads,STREAM_CANCEL_MS);let terminationResult=await treeTermination;if(!treeAlreadyConfirmed&&(!terminationResult.completed||!terminationResult.value))return{kind:"unconfirmed-termination"}}if(!collected.completed)return{kind:"cleanup-failed"};return{kind:"collected",stdout:collected.value[0],stderr:collected.value[1]}}async function runExternalTool(options){if(!path93.isAbsolute(options.cwd))return{status:"spawn-error",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool cwd must be absolute"};if(options.abortSignal?.aborted)return{status:"cancelled",exitCode:null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:"external tool execution cancelled before spawn"};let proc,timeoutHandle,abortListener,overflowTreeTermination,exitSettled=!1,settledExitCode=null,runnerTimeoutMs=clampTimeoutMs(options.timeoutMs),spawnTimeoutMs=computeSpawnTimeoutMs(runnerTimeoutMs);try{proc=_internals86.bunSpawn([options.executable,...options.args],{cwd:options.cwd,env:options.env,stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:spawnTimeoutMs,killProcessTree:!0,windowsVerbatimArguments:options.windowsVerbatimArguments});let exitPromise=proc.exited.then((exitCode)=>{return exitSettled=!0,settledExitCode=exitCode,exitCode}),exitRacePromise=exitPromise.then((exitCode)=>({kind:"exit",exitCode})),timeout=new Promise((resolve47)=>{timeoutHandle=_internals86.setTimeout(()=>{if(exitSettled){resolve47({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve47({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve47)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve47({kind:"cancelled"})},options.abortSignal.addEventListener("abort",abortListener,{once:!0}),options.abortSignal.aborted)abortListener()}),terminateOnOverflow=()=>{overflowTreeTermination??=requestTermination(proc,"SIGKILL")},stdoutRead=startBoundedStreamRead(proc.stdout,options.maxStdoutBytes,terminateOnOverflow),stderrRead=startBoundedStreamRead(proc.stderr,options.maxStderrBytes,terminateOnOverflow),exitResult=await Promise.race([exitRacePromise,timeout,cancelled]);if(exitResult.kind==="timeout"||exitResult.kind==="cancelled"){let gracefulTreeTermination=requestTermination(proc,"SIGTERM"),confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_GRACE_MS);if(!overflowTreeTermination)overflowTreeTermination=requestTermination(proc,"SIGKILL");let treeTerminationResult=waitForValueWithin(Promise.all([gracefulTreeTermination,overflowTreeTermination]),TREE_TERMINATION_CONFIRM_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_FORCE_MS);if(confirmedExitCode===null)confirmedExitCode=await waitForExitWithin(exitPromise,TERMINATION_CONFIRM_MS);let treeTermination=await treeTerminationResult,treeTerminationConfirmed=treeTermination.completed&&treeTermination.value.some(Boolean);Promise.allSettled([stdoutRead.cancel(),stderrRead.cancel()]);let streams2=await collectBoundedStreams(stdoutRead,stderrRead,proc,treeTerminationConfirmed);if(streams2.kind!=="collected")return{status:"spawn-error",exitCode:confirmedExitCode??proc.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams2.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout:stdout2,stderr:stderr2}=streams2;if(confirmedExitCode===null||!treeTerminationConfirmed)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE};if(exitResult.kind==="timeout")return{status:"timeout",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated};return{status:"cancelled",exitCode:confirmedExitCode,stdout:stdout2.text,stderr:stderr2.text,stdoutTruncated:stdout2.truncated,stderrTruncated:stderr2.truncated,message:"external tool execution cancelled"}}let streams=await collectBoundedStreams(stdoutRead,stderrRead,proc);if(streams.kind!=="collected")return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:"",stderr:"",stdoutTruncated:!0,stderrTruncated:!0,message:streams.kind==="unconfirmed-termination"?UNCONFIRMED_TERMINATION_MESSAGE:"external tool output cleanup did not complete"};let{stdout,stderr}=streams;if(overflowTreeTermination){let overflowTermination=await waitForValueWithin(overflowTreeTermination,TREE_TERMINATION_CONFIRM_MS);if(!overflowTermination.completed||!overflowTermination.value)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:UNCONFIRMED_TERMINATION_MESSAGE}}if(proc.spawnError)return{status:"spawn-error",exitCode:proc.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:proc.spawnError.message};if(proc.signalCode)return{status:"spawn-error",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated,message:`external tool terminated by signal ${proc.signalCode}`};return{status:"completed",exitCode:exitResult.exitCode,stdout:stdout.text,stderr:stderr.text,stdoutTruncated:stdout.truncated,stderrTruncated:stderr.truncated}}catch(err){return{status:"spawn-error",exitCode:proc?.exitCode??null,stdout:"",stderr:"",stdoutTruncated:!1,stderrTruncated:!1,message:err instanceof Error?err.message:String(err)}}finally{if(timeoutHandle!==void 0)_internals86.clearTimeout(timeoutHandle);if(abortListener&&options.abortSignal)options.abortSignal.removeEventListener("abort",abortListener);if(!exitSettled)killProcess(proc)}}var DEFAULT_WINDOWS_EXTENSIONS,TERMINATION_GRACE_MS=20,TERMINATION_FORCE_MS=20,TERMINATION_CONFIRM_MS=20,TREE_TERMINATION_CONFIRM_MS=5100,TERMINATION_FALLBACK_BUFFER_MS=1,STREAM_DRAIN_MS=50,STREAM_CANCEL_MS=50,MAX_TIMEOUT_MS2=2147483647,TERMINATION_WINDOWS_MS,MAX_RUNNER_TIMEOUT_MS,UNCONFIRMED_TERMINATION_MESSAGE="external tool process termination could not be confirmed",_internals86;var init_external_tool_runner=__esm(()=>{init_bun_compat();init_logger();DEFAULT_WINDOWS_EXTENSIONS=[".exe",".cmd",".bat"],TERMINATION_WINDOWS_MS=TERMINATION_GRACE_MS+TERMINATION_FORCE_MS+TERMINATION_CONFIRM_MS+TREE_TERMINATION_CONFIRM_MS+TERMINATION_FALLBACK_BUFFER_MS,MAX_RUNNER_TIMEOUT_MS=MAX_TIMEOUT_MS2-TERMINATION_WINDOWS_MS;_internals86={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs,warn}});import*as fsp3 from"node:fs/promises";import*as path94 from"node:path";function boundPath(value){let cleaned=value.replace(/[\p{Cc}]/gu," ").replace(/[`<>]/g," ").replace(/\s+/g," ").trim();return cleaned.length>MAX_EVIDENCE_PATH_LENGTH?`${cleaned.slice(0,MAX_EVIDENCE_PATH_LENGTH)}...`:cleaned}function evidence(parsed,worktreeRoot,gitDir,operations,detail){let allPaths=parsed?[...parsed.unmergedPaths,...parsed.dirtySubmodulePaths,...parsed.dirtyTrackedPaths,...parsed.untrackedPaths]:[],uniquePaths=[...new Set(allPaths)].map(boundPath);return{worktreeRoot:worktreeRoot?boundPath(worktreeRoot):null,gitDir:gitDir?boundPath(gitDir):null,operations,unmergedCodes:parsed?[...new Set(parsed.unmergedCodes)].sort():[],paths:uniquePaths.slice(0,MAX_EVIDENCE_PATHS),trackedCount:parsed?.dirtyTrackedPaths.length??0,untrackedCount:parsed?.untrackedPaths.length??0,pathsTruncated:uniquePaths.length>MAX_EVIDENCE_PATHS,...detail?{detail}:{}}}async function runGitCapture(directory,args2){let result=await runExternalTool({executable:resolveGitExecutable(),args:[...args2],cwd:path94.resolve(directory),timeoutMs:GIT_TIMEOUT_MS3,maxStdoutBytes:MAX_GIT_OUTPUT_BYTES,maxStderrBytes:65536});return{ok:result.status==="completed"&&result.exitCode===0&&!result.stdoutTruncated&&!result.stderrTruncated,stdout:result.stdout}}async function activeOperations(gitDir){return(await Promise.all(OPERATION_MARKERS.map(async([name,marker])=>{try{return await fsp3.lstat(path94.join(gitDir,marker)),name}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}))).filter((value)=>value!==null)}async function classifyPrWorkflowGitState(directory,options={}){let[statusResult,rootResult,gitDirResult]=await Promise.all([_internals87.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals87.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals87.runGitCapture(directory,["rev-parse","--absolute-git-dir"])]);if(!statusResult.ok||!rootResult.ok||!gitDirResult.ok)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Confirm this is a readable Git worktree and resolve filesystem or Git errors before starting the PR workflow.",evidence:evidence(null,null,null,[],"required Git inspection failed")};let worktreeRoot=rootResult.stdout.trim(),gitDir=gitDirResult.stdout.trim(),parsedRaw=parsePorcelainV2Snapshot(statusResult.stdout);if(!worktreeRoot||!gitDir||!parsedRaw)return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the malformed or incomplete Git status before starting the PR workflow.",evidence:evidence(parsedRaw,worktreeRoot||null,gitDir||null,[],"Git returned an incomplete status snapshot")};let ignoredPaths=new Set((options.ignoredPaths??[]).map((value)=>value.replace(/\\/g,"/"))),keepPath=(value)=>!ignoredPaths.has(value.replace(/\\/g,"/")),parsed={...parsedRaw,dirtyTrackedPaths:parsedRaw.dirtyTrackedPaths.filter(keepPath),untrackedPaths:parsedRaw.untrackedPaths.filter(keepPath),unmergedPaths:parsedRaw.unmergedPaths.filter(keepPath),dirtySubmodulePaths:parsedRaw.dirtySubmodulePaths.filter(keepPath)},operations;try{operations=await _internals87.activeOperations(path94.resolve(gitDir))}catch{return{kind:"indeterminate",code:"GIT_STATE_INDETERMINATE",retryable:!1,requiredAction:"Resolve the unreadable Git operation state before starting the PR workflow.",evidence:evidence(parsed,worktreeRoot,gitDir,[],"Git operation markers could not be inspected")}}let stateEvidence=evidence(parsed,worktreeRoot,gitDir,operations);if(parsed.unmergedCodes.length>0)return{kind:"recovery-required",code:"UNMERGED_INDEX",retryable:!1,requiredAction:"Resolve or abort the current merge/rebase/cherry-pick/revert operation manually; conflicted index entries must never be stashed by PR workflow startup.",evidence:stateEvidence};if(operations.length>0)return{kind:"recovery-required",code:"GIT_OPERATION_IN_PROGRESS",retryable:!1,requiredAction:"Complete or abort the active Git operation manually before starting the PR workflow.",evidence:stateEvidence};if(parsed.dirtySubmodulePaths.length>0)return{kind:"recovery-required",code:"DIRTY_SUBMODULE",retryable:!1,requiredAction:"Resolve or preserve dirty submodule worktrees manually; the checkout-preparation stash cannot safely preserve them.",evidence:stateEvidence};if([...parsed.dirtyTrackedPaths,...parsed.untrackedPaths].find((candidate)=>candidate===".swarm"||candidate.startsWith(".swarm/")||candidate.startsWith(".swarm\\")))return{kind:"recovery-required",code:"SWARM_STATE_TRACKING_ERROR",retryable:!1,requiredAction:"Restore .swarm/ so it is git-excluded before starting the PR workflow; runtime state must not be treated as checkout dirt.",evidence:stateEvidence};if(parsed.dirtyTrackedPaths.length===0&&parsed.untrackedPaths.length===0)return{kind:"clean",code:"CLEAN",retryable:!0,requiredAction:"No checkout recovery is required.",evidence:stateEvidence};return{kind:"stashable",code:"STASHABLE_CHANGES",retryable:!0,requiredAction:"Run prepare_pr_workflow_checkout once to preserve the ordinary working-tree changes before checkout.",evidence:stateEvidence}}var GIT_TIMEOUT_MS3=5000,MAX_GIT_OUTPUT_BYTES=524288,MAX_EVIDENCE_PATHS=20,MAX_EVIDENCE_PATH_LENGTH=240,OPERATION_MARKERS,_internals87;var init_pr_workflow_state=__esm(()=>{init_workspace_snapshot();init_external_tool_runner();init_git_executable();OPERATION_MARKERS=[["merge","MERGE_HEAD"],["rebase-merge","rebase-merge"],["rebase-apply-or-am","rebase-apply"],["cherry-pick","CHERRY_PICK_HEAD"],["revert","REVERT_HEAD"],["bisect","BISECT_START"],["sequencer","sequencer"]];_internals87={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash44}from"node:crypto";function computeRedactionPolicyVersion(policy){return 2000000+SECRET_PATTERNS.length*2+(policy.rejectDurableSecrets?1:0)+(policy.detectPii?4:0)+(policy.rejectDurablePii?8:0)+(policy.piiDetector==="ner"?16:0)}function classifyStoredFingerprintAlgorithmVersion(rawStoredVersion,currentVersion=_internals88.currentAlgorithmVersion){let storedVersion=rawStoredVersion===void 0?LEGACY_FINGERPRINT_ALGORITHM_VERSION:rawStoredVersion;if(typeof storedVersion!=="number"||!Number.isFinite(storedVersion))return{status:"unknown"};return storedVersion===currentVersion?{status:"comparable"}:{status:"mismatch",storedVersion,currentVersion}}function computeMemoryCohortFingerprint(input){let canonical=stableCanonicalStringify(input);return createHash44("sha256").update(canonical).digest("hex").slice(0,12)}function buildMemoryCohortFingerprintInput(config2){return{provider:config2.provider,redaction_policy_version:computeRedactionPolicyVersion({rejectDurableSecrets:config2.redaction.rejectDurableSecrets,detectPii:config2.redaction.detectPii,rejectDurablePii:config2.redaction.rejectDurablePii,piiDetector:config2.redaction.piiDetector}),embedding_model:config2.embeddings.model,embedding_dimension:config2.embeddings.dimension,embedding_version:config2.embeddings.version??"default"}}function findSecrets(text){let findings=[];for(let{type,pattern}of SECRET_PATTERNS){pattern.lastIndex=0;for(let match of text.matchAll(pattern))if(match[0])findings.push({type,match:match[0]})}return findings}function containsSecret(text){return findSecrets(text).length>0}function redactSecrets(text){let redacted=text;for(let{type,pattern}of SECRET_PATTERNS)pattern.lastIndex=0,redacted=redacted.replace(pattern,`[REDACTED:${type}]`);return redacted}var SECRET_PATTERNS,FINGERPRINT_ALGORITHM_VERSION=2,LEGACY_FINGERPRINT_ALGORITHM_VERSION=1,_internals88;var init_redaction=__esm(()=>{SECRET_PATTERNS=[{type:"openai_api_key",pattern:/\bsk-[A-Za-z0-9_-]{20,}\b/g},{type:"github_token",pattern:/\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_[A-Za-z0-9_]{20,}\b/g},{type:"aws_access_key_id",pattern:/\bAKIA[0-9A-Z]{16}\b/g},{type:"private_key_block",pattern:/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/g},{type:"authorization_bearer",pattern:/\bAuthorization\s*:\s*Bearer\s+[A-Za-z0-9._~+/=-]{12,}/gi},{type:"env_secret",pattern:/\b(?:[A-Z][A-Z0-9]+_)+(?:KEY|TOKEN|SECRET|PASSWORD)\b\s*=\s*["']?[^\s"'`]{8,}["']?/gi},{type:"gitlab_token",pattern:/\bgl(?:pat|ptt)-[A-Za-z0-9_-]{15,}\b/g},{type:"slack_token",pattern:/\bxox[abprs]-[A-Za-z0-9-]{10,}\b/g},{type:"jwt_token",pattern:/\beyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\b/g},{type:"aws_secret_access_key",pattern:/\b(?:aws_secret_access_key|AWS_SECRET_ACCESS_KEY|secret_access_key|SecretAccessKey)"?\s*[=:]\s*["']?[A-Za-z0-9/+=]{40}\b/g},{type:"aws_secret_access_key_context",pattern:/\bAKIA[0-9A-Z]{16}\b[^\n]{0,200}?\b[A-Za-z0-9/+=]{40}\b/g},{type:"stripe_secret_key",pattern:/\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{24,}\b/g},{type:"google_api_key",pattern:/\bAIza[0-9A-Za-z_-]{35}\b/g},{type:"openssh_private_key_block",pattern:/-----BEGIN[ ]OPENSSH[ ]PRIVATE[ ]KEY-----[\s\S]*?-----END[ ]OPENSSH[ ]PRIVATE[ ]KEY-----/g}];_internals88={currentAlgorithmVersion:FINGERPRINT_ALGORITHM_VERSION}});import{createHash as createHash45,randomUUID as randomUUID15}from"node:crypto";import*as fsp4 from"node:fs/promises";import*as path95 from"node:path";function normalizeSessionID(sessionID){let normalized=sessionID.trim();if(!normalized)throw Error("BLOCKED: PR workflow gate requires a non-empty sessionID");return normalized}function prWorkflowSessionFileStem(sessionID){let normalized=normalizeSessionID(sessionID),slug=normalized.replace(/[^A-Za-z0-9_.-]/g,"_").slice(0,80)||"session",digest3=createHash45("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest3}`}function workflowGateStateRelativePath(sessionID){return path95.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function workflowGateStateLockRelativePath(sessionID){return path95.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowCheckoutMutationLockRelativePath(){return path95.join(WORKFLOW_GATE_DIR,"checkout.lock")}function workflowGateStatePath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateRelativePath(sessionID))}function workflowGateStateImportedPath(directory,sessionID){return`${workflowGateStatePath(directory,sessionID)}.imported`}function workflowGateStateProjectionMarkerPath(directory,sessionID){return`${workflowGateStatePath(directory,sessionID)}.sqlite-projection`}function workflowGateStateCoordinationNamespace(sessionID){return`${WORKFLOW_STATE_COORDINATION_PREFIX}:${prWorkflowSessionFileStem(sessionID)}`}function workflowGateStateLockPath(directory,sessionID){return validateSwarmPath(directory,workflowGateStateLockRelativePath(sessionID))}function workflowCheckoutMutationLockPath(directory){return validateSwarmPath(directory,workflowCheckoutMutationLockRelativePath())}function isoNow(){return new Date().toISOString()}function delay(ms){return new Promise((resolve49)=>setTimeout(resolve49,ms))}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path95.normalize(path95.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}function stateCacheKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}\x00${normalizeSessionID(sessionID)}`}function rememberState(directory,state){let cacheKey=stateCacheKey(directory,state.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state);while(trackedStatesByProjectSession.size>MAX_TRACKED_SESSIONS2){let oldestKey=trackedStatesByProjectSession.keys().next().value;if(!oldestKey)break;trackedStatesByProjectSession.delete(oldestKey)}}function forgetTrackedPrWorkflowState(directory,sessionID){trackedStatesByProjectSession.delete(stateCacheKey(directory,sessionID))}function resetPrReviewPersistenceCaches(){trackedStatesByProjectSession.clear(),pendingStateMutationsByProjectSession.clear(),pendingCheckoutMutationsByProject.clear(),completedCheckoutLockOwners.clear()}function defaultIsProcessAlive(pid){try{return process.kill(pid,0),!0}catch(error49){return error49.code!=="ESRCH"}}function bindPrReviewPersistenceHooks(nextHooks){hooks=nextHooks}function bindPrReviewStateCodec(nextCodec){codec2=nextCodec}function requireCodec(){if(!codec2)throw Error("BLOCKED: PR workflow persistence codec is not bound (the gate must bind it at module init)");return codec2}async function ensurePrWorkflowSafeParentDirectory(directory,filePath){let swarmRoot=path95.resolve(directory,".swarm"),parentPath=path95.dirname(path95.resolve(filePath)),relativeParent=path95.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path95.sep}`)||path95.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp4.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path95.sep).filter(Boolean)){let nextPath=path95.join(currentPath,segment);await hooks.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp4.mkdir(nextPath)}catch(error49){if(error49.code!=="EEXIST")throw error49}await assertSafeDirectory(currentPath,currentIdentity);let nextIdentity=await assertSafeDirectory(nextPath,void 0),[realCurrent,realNext]=await Promise.all([fsp4.realpath(currentPath),fsp4.realpath(nextPath)]);if(normalizeComparableFsPath(path95.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp4.realpath(swarmRoot),realParent=await fsp4.realpath(parentPath),relativeRealParent=path95.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path95.sep}`)||path95.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat11=await fsp4.lstat(directoryPath,{bigint:!0});if(stat11.isSymbolicLink()||!stat11.isDirectory()||expectedIdentity&&!sameBigIntFileIdentity(stat11,expectedIdentity))throw Error("BLOCKED: PR workflow .swarm path must be a real directory and must not change during the operation");return{dev:stat11.dev,ino:stat11.ino}}async function assertOpenedSwarmFileIdentity(directory,filePath,handle,expectedParent,label){let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile())throw Error(`BLOCKED: ${label} is not a file`);return await assertClosedSwarmFileIdentity(directory,filePath,openedStat,expectedParent,label),{dev:openedStat.dev,ino:openedStat.ino}}async function assertClosedSwarmFileIdentity(directory,filePath,expectedIdentity,expectedParent,label){if(!expectedIdentity)throw Error(`BLOCKED: ${label} has no identity`);let[stat11,realRoot,realFile,realParent]=await Promise.all([fsp4.lstat(filePath,{bigint:!0}),fsp4.realpath(path95.resolve(directory,".swarm")),fsp4.realpath(filePath),fsp4.realpath(path95.dirname(filePath))]),relativeFile=path95.relative(realRoot,realFile);if(stat11.isSymbolicLink()||!stat11.isFile()||!sameBigIntFileIdentity(stat11,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path95.sep}`)||path95.isAbsolute(relativeFile))throw Error(`BLOCKED: ${label} changed or escaped .swarm`)}async function writeAtomicJson2(directory,filePath,value){let safeParent=await ensurePrWorkflowSafeParentDirectory(directory,filePath),tempPath=`${filePath}.tmp.${process.pid}.${randomUUID15()}`,tempIdentity,lastError;try{let handle=await fsp4.open(tempPath,"wx");try{await hooks.beforeAtomicTempWrite?.(),tempIdentity=await assertOpenedSwarmFileIdentity(directory,tempPath,handle,safeParent,"PR workflow atomic temporary file"),await handle.writeFile(JSON.stringify(value,null,2),"utf-8"),await handle.sync()}finally{await handle.close()}await hooks.beforeAtomicRename?.(),await assertClosedSwarmFileIdentity(directory,tempPath,tempIdentity,safeParent,"PR workflow atomic temporary file");for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await hooks.rename(tempPath,filePath),lastError=void 0;break}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")break;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}if(lastError)throw lastError;await assertClosedSwarmFileIdentity(directory,filePath,tempIdentity,safeParent,"PR workflow atomic destination file")}finally{try{await fsp4.rm(tempPath,{force:!0})}catch{}}}async function writePrWorkflowAtomicJson(directory,filePath,value){await writeAtomicJson2(directory,filePath,value)}async function readPrWorkflowGateStateFromDisk(directory,sessionID,options={}){let authoritative=await readPrWorkflowGateStateFromCoordination(directory,sessionID);if(authoritative)return await repairImportedWorkflowGateShadow(directory,sessionID,authoritative),authoritative;return importLegacyPrWorkflowGateStateIfNeeded(directory,sessionID,options.allowSalvagedImport===!0)}async function readPrWorkflowGateStateFileRawFromDisk(filePath,stateLabel){let raw;try{raw=await fsp4.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" is not valid JSON`)}let parsed=requireCodec().safeParse(parsedJson);if(!parsed.success)throw Error(`BLOCKED: PR workflow gate state for session "${stateLabel}" is invalid`);return parsed.data}async function readPrWorkflowGateStateFileFromDisk(filePath,stateLabel){return readPrWorkflowGateStateFileRawFromDisk(filePath,stateLabel)}async function readPrWorkflowGateStateFromCoordination(directory,sessionID){return readPrWorkflowGateStateCoordinationRow(directory,sessionID)?.state??null}function readPrWorkflowGateStateCoordinationRow(directory,sessionID){let row=getCoordinationState(directory,workflowGateStateCoordinationNamespace(sessionID),WORKFLOW_STATE_ENTITY_KEY);if(!row)return null;let parsedJson;try{parsedJson=JSON.parse(row.payload)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is not valid JSON`)}let parsed=requireCodec().safeParse(parsedJson);if(!parsed.success||parsed.data.revision!==row.generation)throw Error(`BLOCKED: PR workflow gate state for session "${sessionID}" is invalid`);return{rowRevision:row.revision,state:parsed.data}}function workflowStateStatus(state){let mode=state.mode;return typeof mode==="string"&&mode.trim().length>0?mode:"active"}async function fileExists(filePath){try{return await fsp4.stat(filePath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeWorkflowGateState(state){return JSON.stringify(state,null,2)}async function readTextFileIfExists(filePath){try{return await fsp4.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker(directory,filePath){await ensurePrWorkflowSafeParentDirectory(directory,filePath),await fsp4.writeFile(filePath,`sqlite-projection
1250
1251
  `,"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 ${path95.basename(filePath)}`)}async function archiveShadowSource(filePath){if(!await fileExists(filePath))return;await renameWithRetry6(filePath,await collisionSafeImportedPath(filePath))}async function syncWorkflowGateShadowProjection(directory,sessionID,state,options){let filePath=workflowGateStatePath(directory,sessionID);if(options.archiveLegacy&&await fileExists(filePath))await archiveShadowSource(filePath);await writeAtomicJson2(directory,filePath,state),await writeProjectionMarker(directory,workflowGateStateProjectionMarkerPath(directory,sessionID))}async function repairImportedWorkflowGateShadow(directory,sessionID,state){let filePath=workflowGateStatePath(directory,sessionID),markerPath=workflowGateStateProjectionMarkerPath(directory,sessionID),live=await readTextFileIfExists(filePath);if(live===null){await syncWorkflowGateShadowProjection(directory,sessionID,state,{archiveLegacy:!1});return}let canonicalImportedExists=await fileExists(workflowGateStateImportedPath(directory,sessionID)),markerExists=await fileExists(markerPath),projected=serializeWorkflowGateState(state);if(canonicalImportedExists&&markerExists&&live===projected)return;if(canonicalImportedExists&&live===projected){await writeProjectionMarker(directory,markerPath);return}await syncWorkflowGateShadowProjection(directory,sessionID,state,{archiveLegacy:!0})}async function importLegacyPrWorkflowGateStateIfNeeded(directory,sessionID,allowSalvagedImport=!1){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp4.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:createHash45("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,state,options={}){let bound=requireCodec(),validated=bound.parse(state),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=readPrWorkflowGateStateCoordinationRow(directory,normalizedSessionID),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");if(currentAuthoritative){if(!deleteCoordinationState(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY,currentAuthoritative.rowRevision))throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying")}try{await fsp4.rm(workflowGateStatePath(directory,normalizedSessionID),{force:!0})}catch(error49){if(error49.code!=="ENOENT")throw error49}forgetTrackedPrWorkflowState(directory,normalizedSessionID)}function checkoutMutationProjectKey(directory){return canonicalRootKeyFresh(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve49)=>{timeout=setTimeout(()=>{resolve49({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((resolve49)=>{release=resolve49}),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 fsp4.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp4.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((resolve49)=>{release=resolve49}),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 fsp4.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 fsp4.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp4.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp4.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 fsp4.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,trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,defaultPersistenceHooks,hooks,codec2,PrWorkflowCheckoutMutationTimeoutError;var init_persistence=__esm(()=>{init_coordination_store();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)=>fsp4.open(lockPath,"wx"),removeCheckoutLock:(lockPath)=>fsp4.rm(lockPath),checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,rename:(from,to)=>fsp4.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 createHash46,randomUUID as randomUUID16}from"node:crypto";import*as fsp5 from"node:fs/promises";import*as path96 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 relative25=path96.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`);return validateSwarmPath(directory,relative25)}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 fsp5.stat(filePath);if(!stat12.isFile()||stat12.size>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store is not a bounded regular file");raw=await fsp5.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<=_internals89.renameRetryDelaysMs.length;attempt++)try{await _internals89.renameImpl(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES4.has(code))throw err;if(attempt<_internals89.renameRetryDelaysMs.length)await new Promise((resolve49)=>setTimeout(resolve49,_internals89.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 fsp5.mkdir(path96.dirname(filePath),{recursive:!0});let tempPath=path96.join(path96.dirname(filePath),`.${path96.basename(filePath)}.${randomUUID16()}.tmp`);try{await fsp5.writeFile(tempPath,serialized2,{encoding:"utf8",flag:"wx"}),await renameWithRetryAsync(tempPath,filePath)}finally{await fsp5.rm(tempPath,{force:!0}).catch(()=>{return})}}async function fileExists2(filePath){try{return await fsp5.stat(filePath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeAuthorizationFile(file2){return`${JSON.stringify(file2,null,2)}
1251
1252
  `}async function readTextFileIfExists2(filePath){try{return await fsp5.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker2(filePath){await fsp5.mkdir(path96.dirname(filePath),{recursive:!0}),await fsp5.writeFile(filePath,`sqlite-projection
1252
- `,"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 ${path96.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 fsp5.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:path96.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`),sourceDigest:createHash46("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,_internals89;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"]);_internals89={AUTHORIZATION_TTL_MS,MAX_ACTIVE_AUTHORIZATIONS,reentryAuthorizationFilePath,reentryAuthorizationCoordinationNamespace,pruneAuthorizations,authorizationMatchesBinding,hasPrReviewReentryAuthorizationAgainstBinding,renameImpl:(from,to)=>fsp5.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"}}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 createHash47}from"node:crypto";import{readFileSync as readFileSync36}from"node:fs";import*as fsp6 from"node:fs/promises";import*as path97 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,state){return requireBoundHelpers().createPrReviewGateContext(directory,state)}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,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics){return requireBoundHelpers().successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics)}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers().recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function validatePrReviewDiscoveryLaneCompletion(input){return requireBoundHelpers().validatePrReviewDiscoveryLaneCompletion(input)}function validateExactStructuredReceiptCoverage(input){return requireBoundHelpers().validateExactStructuredReceiptCoverage(input)}function allowedPrReviewReportVerdicts(kind){if(kind==="COMPLETE")return PR_REVIEW_REPORT_VERDICTS;if(kind==="PARTIAL")return["REQUEST_CHANGES","INCOMPLETE"];return["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,state,revisionDigest){let successful2=new Set,inFlight=new Set,contractFailed=new Set,contractRetried=new Set(state.prReviewContractRetryDimensions??[]),dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)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,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified,state)).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});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}}function hasRevisionIndependentDiscoverySemantics(directory,qualified,state){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:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:artifact.revisionDigest,workflowInstanceId:state.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope:state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0}}).ok}function latestTypedFailureForBaseDimension(directory,state,dimension){let latest=null;for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){if(!((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).includes(dimension))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record2.terminalResult,failureClass=(terminal?.result??record2.result)?.workflowLaneFailureClass;if(!terminal||!failureClass||terminal.status==="completed")continue;let candidate={failureClass,terminalEventId:terminal.eventId,recordedAt:terminal.recordedAt,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,state,revisionDigest,dimension){let latest=null,reviewScope=state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;for(let batch of state.prReviewBaseDispatches??[]){let records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});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:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest,workflowInstanceId:state.workflowInstanceId,workflowRevision:record2.workflowGeneration,baseSha:state.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 path97.join("pr-review",runId,"coverage-disclosure.json")}function derivePrReviewDimensionSettlement(directory,state,revisionDigest){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest),cancellations=state.prReviewDimensionCancellations??{},dispatched=new Set;for(let batch of state.prReviewBaseDispatches??[]){let records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(!records.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,state,dimension),latestStructuredUnresolved=latestStructuredReceiptUnresolvedForBaseDimension(directory,state,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}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}}async function readAndVerifyCoverageDisclosure(directory,state){let{prReviewPartialBaseCoverage:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state;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(path97.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(createHash47("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 state=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim());if(!state||state.mode!=="PR_REVIEW"||!state.prHeadSha)throw Error("BLOCKED: partial base coverage requires an active head-bound PR_REVIEW workflow");let normalizedRunId=PrReviewRunIdSchema.parse(runId);if(state.prReviewReservedRunId&&state.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,state),settlement=derivePrReviewDimensionSettlement(directory,state,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"&&!state.prReviewDimensionCancellations?.[entry.dimension])throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" declared CANCELLED without a persisted cancellation record`)}let existing=await readAndVerifyCoverageDisclosure(directory,state);if(existing){if(existing.runId===normalizedRunId&&existing.prHeadSha===state.prHeadSha&&existing.revisionDigest===ctx.revisionDigest&&JSON.stringify(existing.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions))return state;throw Error("BLOCKED: partial base coverage admission differs from the immutable existing disclosure")}let record2={schemaVersion:2,runId:normalizedRunId,prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path97.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 fsp6.readFile(absolutePath,"utf8")===raw)await fsp6.rm(absolutePath,{force:!0})}catch{}};try{if(readFileSync36(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=createHash47("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state,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 state=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record2=state?.prReviewPartialBaseCoverage;if(!state||!record2||record2.runId!==options.runId)return!1;if((state.prReviewArtifactBoundaries??[]).includes(options.boundary))return!1;if(state.prReviewCoverageDisclosurePath!==options.relativePath||state.prReviewCoverageDisclosureDigest!==options.digest)return!1;let absolutePath=validateSwarmPath(directory,options.relativePath);try{let raw=await fsp6.readFile(absolutePath,"utf8");if(createHash47("sha256").update(raw,"utf8").digest("hex")!==options.digest)return!1}catch(error49){if(error49.code!=="ENOENT")throw error49}return await fsp6.rm(absolutePath,{force:!0}),await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewPartialBaseCoverage:void 0,prReviewCoverageDisclosurePath:void 0,prReviewCoverageDisclosureDigest:void 0}),!0})}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if((state.prReviewBaseDispatches??[]).length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,ctx.revisionDigest);if(settlement.kind==="COMPLETE")return{state,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,state),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===state.prHeadSha&&disclosure.revisionDigest===ctx.revisionDigest&&disclosure.runId===(state.prReviewArtifactRunId??state.prReviewReservedRunId))return{state,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 state=await readPrWorkflowGateStateFromDisk2(directory,normalizeSessionID(sessionID));if(!state||state.mode!=="PR_REVIEW"||!state.prHeadSha)return null;let ctx=await createPrReviewGateContext(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,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_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"},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"]).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 createHash48}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,state,ctx){return requireBoundHelpers2().derivePrReviewCandidateInventory(directory,state,ctx)}function derivePrReviewCriticInventory(directory,state,ctx){return requireBoundHelpers2().derivePrReviewCriticInventory(directory,state,ctx)}function authoritativeReviewerClaims(directory,state,ctx){return requireBoundHelpers2().authoritativeReviewerClaims(directory,state,ctx)}function reviewerSubagentSessionIds(directory,state){return requireBoundHelpers2().reviewerSubagentSessionIds(directory,state)}function prReviewPhaseWindow(state,phase){return requireBoundHelpers2().prReviewPhaseWindow(state,phase)}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){return requireBoundHelpers2().batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)}function recordsPassingBatchIntegrity2(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers2().recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state,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,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity2(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],{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 createHash48("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,state,batchId,laneId,itemIds){let record2=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).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,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let delegation=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).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(state,effects=[]){return{status:"applied",state,effects}}function rejected(state,code,detail){return{status:"rejected",state,rejection:{code,detail}}}function currentGeneration(state){return state.revision}function circuitRecordOf(state){let circuit=state.prReviewResilience?.circuit;if(!circuit||!("version"in circuit))return null;return circuit}function withCircuit(state,circuit){if(!state.prReviewResilience)return state;return{...state,prReviewResilience:{...state.prReviewResilience,circuit}}}function reducePrReviewEvent(state,event){switch(event.type){case"base_admission_requested":{let dispatches=state.prReviewBaseDispatches??[];if(dispatches.length>=event.maxBatches)return rejected(state,"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({...state,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record2},[{kind:"persist_state"}])}case"base_admission_rolled_back":{let dispatches=state.prReviewBaseDispatches??[];if(dispatches.at(-1)?.batchId!==event.batchId)return rejected(state,"rollback_preconditions_failed",`the last admitted base batch is not ${event.batchId}`);if(event.batchDelegationRecordsExist)return rejected(state,"rollback_preconditions_failed",`base batch ${event.batchId} already has delegation records`);let nextDispatches=dispatches.slice(0,-1);return applied({...state,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:dispatches.at(-2)},[{kind:"persist_state"}])}case"collection_observed":return applied(state,[{kind:"emit_diagnostic",source:"collection_observer",code:`collection_${event.diagnostic}`,boundedDetail:event.boundedDetail}]);case"lane_structured_result_submitted":{if(event.generation!==currentGeneration(state))return rejected(state,"stale_generation_result",`result generation ${event.generation} does not match the active generation ${currentGeneration(state)}`);if(event.existingReceiptDigest!==void 0){if(event.existingReceiptDigest===event.semanticEnvelopeDigest)return applied(state,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed",replay:!0}]);return rejected(state,"duplicate_conflicting_result",`lane ${event.laneId} already carries a different structured receipt`)}if(event.outcome==="INCOMPLETE")return applied(state);return applied(state,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed"}])}case"transcript_evidence_presented":{if(event.laneHasStructuredReceipt)return rejected(state,"receipt_cannot_be_downgraded",`lane ${event.laneId} has a structured receipt; transcript evidence cannot alter it`);return applied(state)}case"provider_terminal_observed":{if(event.evidence.source==="observer_deadline")return rejected(state,"observer_deadline_not_terminal_evidence","a collection wait deadline is never terminal provider evidence");if(event.evidence.source==="client_unavailable")return rejected(state,"client_absence_not_terminal_evidence","an unavailable host messages client is never terminal provider evidence");if(event.evidence.source==="parser_or_transcript")return rejected(state,"parser_failure_not_provider_signal","parser/transcript rejection is never a provider circuit signal");if(event.evidence.source==="stale_observation")return rejected(state,"stale_observation_not_provider_signal","a presumed-stale sweep is never terminal provider evidence");if(event.generation!==currentGeneration(state))return rejected(state,"stale_generation_result",`terminal evidence generation ${event.generation} is not the active generation`);return applied(state)}case"lane_cancelled":{if(event.generation!==currentGeneration(state))return rejected(state,"stale_generation_result",`cancellation generation ${event.generation} does not match the active generation`);return applied(state,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"cancelled"}])}case"circuit_advance_requested":{let adoption=adoptPrReviewCircuit(state.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=state;if(adoption.kind==="migrated")next=withCircuit(state,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(state);if(!circuit||circuit.state!=="HALF_OPEN"||!circuit.probe)return applied(state);if(event.outcome.result==="rolled_back_admission")return applied(withCircuit(state,rollbackPrReviewCircuitProbe(circuit,event.nowMs,event.policy.circuitOpenDurationMs??60000)),[{kind:"persist_state"}]);return applied(state)}case"resilience_config_changed":{if(!event.enabled){if(!state.prReviewResilience)return applied(state);if(state.prReviewResilience.policy.enabled===!1)return applied(state);return applied({...state,prReviewResilience:{...state.prReviewResilience,policy:{...state.prReviewResilience.policy,enabled:!1}}},[{kind:"persist_state"}])}let policy=resolvePrReviewResiliencePolicy(event.policy);return applied({...state,prReviewResilience:{policy,attempts:[],circuit:resetPrReviewResilienceForReEnable({previousCircuit:circuitRecordOf(state),policy,nowMs:event.nowMs})}},[{kind:"persist_state"}])}case"coverage_finalization_requested":{let{settlement}=event;if(settlement.liveDimensions.length>0)return rejected(state,"live_lane_blocks_coverage",`coverage finalization blocked by live dimension(s): ${settlement.liveDimensions.join(", ")}`);if(event.requestedVerdict==="APPROVE"){if(settlement.kind==="PARTIAL")return rejected(state,"partial_coverage_cannot_approve","a partial review can never emit APPROVE");if(settlement.kind==="NO_COVERAGE")return rejected(state,"no_coverage_cannot_approve","a zero-coverage report can never emit APPROVE")}return applied(state,[{kind:"persist_state"}])}case"critic_result_recorded":{let unfulfilled=event.criticRequiredFindingIds.filter((id)=>!event.criticConfirmedFindingIds.includes(id));if(unfulfilled.length>0)return rejected(state,"critic_required_unfulfilled",`critic confirmation missing for finding(s): ${unfulfilled.join(", ")}`);return applied(state,[{kind:"persist_state"}])}case"publication_armed":{if(event.verdict==="APPROVE"&&event.coverageKind!=="COMPLETE")return rejected(state,event.coverageKind==="NO_COVERAGE"?"no_coverage_cannot_approve":"partial_coverage_cannot_approve",`cannot arm publication of ${event.verdict} on ${event.coverageKind} coverage`);return applied(state,[{kind:"persist_state"}])}case"publication_published":case"armed_recovery_requested":case"reviewer_authorization_consumed":{let reason=bindingRejection(state,event);if(reason)return rejected(state,"stale_foreign_authorization",reason.detail);if(event.type==="reviewer_authorization_consumed"&&event.role!==event.expectedRole)return rejected(state,"stale_foreign_authorization",`authorization role ${event.role} does not match the expected role ${event.expectedRole}`);if(event.type==="armed_recovery_requested"){let cancellations={...state.prReviewDimensionCancellations??{}};for(let dimension of event.dimensionsToCancel)cancellations[dimension]={reason:"armed-recovery cancellation of remaining lanes",cancelledAt:event.nowIso,source:"armed_recovery"};return applied({...state,prReviewDimensionCancellations:cancellations},[{kind:"persist_state"}])}return applied(state,[{kind:"persist_state"}])}default:{let exhausted=event;return rejected(state,"unknown_event",`unknown PR-review event discriminant: ${event.type??"(none)"}`)}}}function bindingRejection(state,event){let binding=event.binding;if(binding.sessionID!==state.sessionID)return{detail:`authorization session ${binding.sessionID} is foreign to the active workflow session`};if(binding.workflowInstanceId!==void 0&&state.workflowInstanceId!==void 0&&binding.workflowInstanceId!==state.workflowInstanceId)return{detail:"authorization belongs to a different workflow instance"};if(!state.prHeadSha||binding.prHeadSha!==state.prHeadSha)return{detail:`authorization head ${binding.prHeadSha} does not match the bound head`};if(binding.generation!==currentGeneration(state))return{detail:`authorization generation ${binding.generation} is stale (active: ${currentGeneration(state)})`};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,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,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,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 createHash49,randomUUID as randomUUID17}from"node:crypto";import{readFileSync as readFileSync37,statSync as statSync36}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path98 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(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_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:[path98.join(".swarm",workflowCheckoutMutationLockRelativePath()),path98.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),state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state)rememberState(directory,state);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state}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 preliminary=readDelegations(directory).filter((record3)=>record3.subagentSessionId===child&&record3.correlationId===child&&(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"));if(preliminary.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};let parentSessionId=preliminary[0].parentSessionId,record2=preliminary[0];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 state=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state||state.mode!=="PR_REVIEW"||!state.workflowInstanceId||!state.prHeadSha||!state.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state)).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!==state.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};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(state,{type:"lane_structured_result_submitted",batchId,laneId,generation:state.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{}});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:child,batchId,laneId,expectedWorkflowInstanceId:state.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state.prReviewBaseSha,receipt:{schemaVersion:1,mode:record2.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record2.workflowLane,ownedWorkflowLanes,baseSha:state.prReviewBaseSha,headSha:state.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:child,generation:record2.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await 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),action()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp7.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,path98.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state)continue;let expectedName=path98.basename(workflowGateStateRelativePath(state.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state.sessionID}" has an active ${state.mode} workflow`)}}catch(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,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})})}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(`
1253
- `)){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,tokens=activity?.estimatedTokens??0;if(steps>=watchdog.stall_min_steps||tokens>=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=tokens;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=[];for(let record2 of readDelegations(directory)){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:[]};for(let record2 of readDelegations(directory)){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 state=recovery.state,cancelRevision=null,cancellationObservedRemoteHead;if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,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=state.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(state.mode!=="PR_FEEDBACK"||!state.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(state.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((state.prFeedbackReadyToPublish||recovery.armedShapeUnreadable)&&!options.cancelPublication)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting, 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,state.sessionID,options.laneLiveness),probeRetainedLanes=laneSettlement.probedAliveLaneIds??[],overridesProbeRetention=options.kind==="force"&&laneSettlement.freshOpenLanes===0&&probeRetainedLanes.length>0;if(laneSettlement.openLanes>0&&!overridesProbeRetention){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: ${state.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: ${state.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:state.sessionID,mode:state.mode,kind:options.kind,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},...state.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??state.revision,{allowSalvagedRead:recovery.salvaged})}catch(error49){try{appendCoreEventSync(directory,{type:"pr_workflow_abort_not_completed",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.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,state.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.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:state.mode,...state.prHeadSha?{prHeadSha:state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state)throw noActiveGateError(sessionID);if(request.expectedMode&&state.mode!==request.expectedMode)throw wrongModeError(state,request.expectedMode);let armed=state.prFeedbackReadyToPublish;if(!armed)throw Error(`BLOCKED: ${state.mode} is not armed for publication; armed recovery applies only to an active staged publication authorization (complete or abort normally instead).`);if(request.prHeadSha!==state.prHeadSha)throw Error(`BLOCKED: armed recovery head mismatch: workflow is bound to "${state.prHeadSha??"(none)"}", request declared "${request.prHeadSha}".`);if(state.prReviewBaseSha===void 0!==(request.baseSha===void 0))throw Error(`BLOCKED: armed recovery base mismatch: ${state.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&&state.prReviewBaseSha!==void 0&&request.baseSha!==state.prReviewBaseSha)throw Error(`BLOCKED: armed recovery base mismatch: workflow is merge-base bound to "${state.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!==state.revision)throw Error(`BLOCKED: armed recovery generation mismatch: current gate generation is ${state.revision}, request declared ${request.generation}. Stale requests fail closed; re-read the workflow state and retry.`);if(request.workflowInstanceId===void 0!==(state.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&&state.workflowInstanceId!==void 0&&request.workflowInstanceId!==state.workflowInstanceId)throw Error(`BLOCKED: armed recovery workflow identity mismatch: active workflow is "${state.workflowInstanceId}", request declared "${request.workflowInstanceId}".`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,request.laneLiveness);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=state.prReviewDimensionCancellations;if(state.mode==="PR_REVIEW"&&state.prHeadSha){let ctx=await createPrReviewGateContext2(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,ctx.revisionDigest);for(let entry of settlement.unresolvedDimensions){if(entry.terminalState!=="NOT_LAUNCHED")continue;cancelledDimensions.push(entry.dimension),cancellations={...cancellations,[entry.dimension]:{reason:sanitizedReason,cancelledAt:isoNow(),source:"armed_recovery"}}}}let recoveredAt=isoNow();try{appendCoreEventSync(directory,{type:"pr_workflow_armed_recovery",timestamp:recoveredAt,sessionID:state.sessionID,mode:state.mode,prHeadSha:state.prHeadSha,revisionDigest:armed.revisionDigest,generation:state.revision,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,reason:sanitizedReason})}catch{}return await writeStateWhileLocked(directory,{...state,updatedAt:recoveredAt,prFeedbackReadyToPublish:void 0,prFeedbackArmedRecovery:{recoveredAt,prHeadSha:state.prHeadSha,revisionDigest:armed.revisionDigest,generation:state.revision,reason:sanitizedReason},...cancellations?{prReviewDimensionCancellations:cancellations}:{}}),{mode:state.mode,prHeadSha:state.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),state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,checkoutRecovery:void 0,updatedAt:isoNow()};await _test_exports2.beforePrFeedbackTrackingPersist?.();try{return await writeStateWhileLocked(directory,nextState)}catch(error49){if(!state.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 state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0)throw Error(`BLOCKED: PR_FEEDBACK rebind refused while ${openLanes.length} PR workflow lane(s) are still in flight; collect their results first.`);if(normalizedHead===state.prHeadSha)throw Error(`BLOCKED: PR_FEEDBACK rebind to the current intake head "${normalizedHead}" is a no-op; a rebind must move to a genuinely new verified PR head after merge/rebase repair.`);await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{appendCoreEventSync(directory,{type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state.sessionID,previousPrHeadSha:state.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}catch{}return withSessionStateMutation(directory,state.sessionID,async()=>writeStateWhileLocked(directory,nextState))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports2.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState2(directory,state),state}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 state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}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 batchLaneRecords(directory,state,batchId,laneId){return findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).filter((record2)=>record2.laneId===laneId)}function batchIsTerminal(directory,state,batchId){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID});return records.length>0&&records.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record2.status)||record2.status==="consumed")}function effectivePrReviewResiliencePolicy(state,requestedPolicy){return state.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,state){let signals=[];for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state,batch.batchId,lane.laneId));if(!latest)continue;let signal=classifyPrReviewCircuitSignal(latest);if(signal)signals.push(signal)}return signals}function probeObservationForCircuit(directory,state,circuit){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return;let latest=latestDelegationRecord(batchLaneRecords(directory,state,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,state=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},state=await writeStateWhileLocked(directory,{...state,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(state,{type:"circuit_advance_requested",nowMs:nowMs3,laneSignals:laneSignalsForCircuitReview(directory,state),probeObservation:circuit?.state==="HALF_OPEN"?probeObservationForCircuit(directory,state,circuit):void 0,admission:args2.admission,policy:snapshot.policy});if(advanceOutcome.status==="rejected")return{state,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},state=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot});else state=nextState;if(blockedReason!==void 0)return{state,snapshot,blocked:{reason:blockedReason}};let pendingProbe=nextState.prReviewResilience?.circuit;if(pendingProbe&&"version"in pendingProbe&&pendingProbe.state==="HALF_OPEN"&&pendingProbe.probe)return{state,snapshot,pendingProbeCircuit:pendingProbe};return{state,snapshot}}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,policy,liveResilienceEnabled){let nextState=state,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(),status=session?.status;if(!session||typeof status!=="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()=>status.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,state,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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,state,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state,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 state=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"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((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)throw Error(`BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);let depthTier=state.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(state,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,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,resiliencePolicy,liveResilienceEnabled));if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let nextResilience=state.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state=await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state.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(state,configEvent);if(outcome.status==="applied"&&outcome.effects.some((effect)=>effect.kind==="persist_state"))state=await writeStateWhileLocked(directory,{...outcome.state,updatedAt:isoNow()}),previous=state.prReviewBaseDispatches??[],nextResilience=state.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,state)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]},pendingProbeCircuit;if(liveResilienceEnabled){let outcome=await advanceResilienceCircuitWhileLocked({directory,state,snapshot,admission:{batchId,laneId:normalizedLanes[0]?.laneId??""}});if(state=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,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state,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,state,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,state,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,state,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,state)).revisionDigest,attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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()},nextState={...state,updatedAt:isoNow(),prReviewBaseDispatches:[...previous,record2],prReviewBaseDispatch:record2,...requestedContractRetry?{prReviewContractRetryDimensions:[...state.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 state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_REVIEW")return!1;let batchRecords=findByBatchId(directory,normalizedBatchId,{parentSessionId:normalizedSessionID}),rollbackOutcome=reducePrReviewEvent(state,{type:"base_admission_rolled_back",batchId:normalizedBatchId,batchDelegationRecordsExist:batchRecords.length>0});if(rollbackOutcome.status==="rejected")return!1;let rollbackState=rollbackOutcome.state,currentBaseDispatches=state.prReviewBaseDispatches??[],nextBaseDispatches=rollbackState.prReviewBaseDispatches??[],rolledBackDimensions=new Set(currentBaseDispatches.at(-1)?.lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])??[]),nextContractRetryDimensions=contractRetry?(state.prReviewContractRetryDimensions??[]).filter((dimension)=>!rolledBackDimensions.has(dimension)):state.prReviewContractRetryDimensions,lastAttempt=state.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,{...state,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(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key2 of state.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,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest3=revisionDigest;if(!digest3)digest3=(await createPrReviewGateContext2(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest3=revisionDigest??(await createPrReviewGateContext2(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory2(directory,state,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,state,{revisionDigest:digest3})},pruned=pruneWorkflowBatches(directory,state,digest3);if(!pruned)return state;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"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>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,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function 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 state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext2(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory2(directory,state,ctx):derivePrReviewCriticInventory2(directory,state,ctx),assertStringSetSubset(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};let nextState={...state,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 state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext2(directory,state),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow2(state,requiredPhase);if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){let existing=state.prFeedbackInventory;if(sameStringArray(existing,normalizedInventory))return state;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=state.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={...state,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={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState2(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest3=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest3),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest3).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest3);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState2(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!legacyFeedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettledState(directory,state){if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state,currentDigest),missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return currentDigest}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK");return await assertPrFeedbackVerificationSettledState(directory,state),state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash49("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0},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 state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState2(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!sameStringArray(batch.itemIds,state.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,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}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,state,active,component){switch(component){case"digest":try{let digest3=await currentPrFeedbackRevisionDigest(directory,state);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(state,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,state,active){for(let component of PUBLICATION_IDENTITY_COMPONENTS){let check2=await verifyPublicationIdentityComponent(directory,state,active,component);if(check2.kind!=="intact")return check2}if(!publicationEvidenceJoinIntact(state,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(state,active){if(state.prFeedbackStageA?.validatedAt!==active.evidence.stageAValidatedAt)return!1;for(let join76 of active.evidence.batches){let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===join76.phase);if(!batch||batch.batchId!==join76.batchId||batch.laneId!==join76.laneId)return!1}return!0}function buildPublicationEvidenceJoin(state,currentDigest){let stageA=state.prFeedbackStageA;if(!stageA||stageA.revisionDigest!==currentDigest||!stageA.validatedAt)return null;let batches=[];for(let phase of PR_FEEDBACK_PHASE_ORDER){let batch=[...state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")throw Error("BLOCKED: PR_FEEDBACK publication invalidation requires an active PR_FEEDBACK gate");return applyPublicationInvalidationWhileLocked(directory,state,reason,options)})}async function applyPublicationInvalidationWhileLocked(directory,state,reason,options={}){{let active=state.prFeedbackPublication?.active,legacyRecord=active?void 0:state.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,state,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=(state.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:state.sessionID,intakeHeadSha:state.prHeadSha??"unknown",localHeadRef:"unknown",localHead:legacyRecord.localHead,remoteName:legacyRecord.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacyRecord.remoteBranchRef,remoteRef:legacyRecord.remoteRef,revisionDigest:legacyRecord.revisionDigest,evidence:{stageAValidatedAt:state.prFeedbackStageA?.validatedAt??"unknown",batches:(state.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={...state,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(state.prFeedbackPublication,invalidated,[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_invalidated",sessionID:state.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),state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")return state;if(state.prFeedbackPublication||!state.prFeedbackReadyToPublish)return state;let legacy=state.prFeedbackReadyToPublish;return withSessionStateMutation(directory,normalizedSessionID,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!locked||locked.mode!=="PR_FEEDBACK")return locked??state;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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state?.prFeedbackPublication,active=publication?.active;if(!state||!publication||!active||active.state!=="push_in_flight"||!publication.attempts.some((attempt)=>!attempt.result))return state;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={...state,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state.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(state){let active=state.prFeedbackPublication?.active,history=state.prFeedbackPublication?.history??[],attempts=state.prFeedbackPublication?.attempts??[];if(!active&&!state.prFeedbackReadyToPublish&&history.length===0)return null;let lines=[];if(state.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(`
1253
+ `,"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 ${path96.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 fsp5.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:path96.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`),sourceDigest:createHash46("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,_internals89;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"]);_internals89={AUTHORIZATION_TTL_MS,MAX_ACTIVE_AUTHORIZATIONS,reentryAuthorizationFilePath,reentryAuthorizationCoordinationNamespace,pruneAuthorizations,authorizationMatchesBinding,hasPrReviewReentryAuthorizationAgainstBinding,renameImpl:(from,to)=>fsp5.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"}}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 createHash47}from"node:crypto";import{readFileSync as readFileSync36}from"node:fs";import*as fsp6 from"node:fs/promises";import*as path97 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,state){return requireBoundHelpers().createPrReviewGateContext(directory,state)}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,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics){return requireBoundHelpers().successfulObligationsFromExactBatch(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,expectedRevisionDigest,diagnostics)}function recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers().recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function validatePrReviewDiscoveryLaneCompletion(input){return requireBoundHelpers().validatePrReviewDiscoveryLaneCompletion(input)}function validateExactStructuredReceiptCoverage(input){return requireBoundHelpers().validateExactStructuredReceiptCoverage(input)}function allowedPrReviewReportVerdicts(kind){if(kind==="COMPLETE")return PR_REVIEW_REPORT_VERDICTS;if(kind==="PARTIAL")return["REQUEST_CHANGES","INCOMPLETE"];return["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,state,revisionDigest){let successful2=new Set,inFlight=new Set,contractFailed=new Set,contractRetried=new Set(state.prReviewContractRetryDimensions??[]),dedicatedSuccessful=new Set,terminallyFailed=new Set;for(let batch of state.prReviewBaseDispatches??[]){let batchSuccessful=successfulObligationsFromExactBatch(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);for(let obligation of batchSuccessful)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,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt).filter((qualified)=>hasRevisionIndependentDiscoverySemantics(directory,qualified,state)).map((qualified)=>qualified.record.laneId)),records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});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}}function hasRevisionIndependentDiscoverySemantics(directory,qualified,state){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:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:artifact.revisionDigest,workflowInstanceId:state.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope:state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0}}).ok}function latestTypedFailureForBaseDimension(directory,state,dimension){let latest=null;for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){if(!((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).includes(dimension))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((candidate)=>candidate.laneId===lane.laneId)){let terminal=record2.terminalResult,failureClass=(terminal?.result??record2.result)?.workflowLaneFailureClass;if(!terminal||!failureClass||terminal.status==="completed")continue;let candidate={failureClass,terminalEventId:terminal.eventId,recordedAt:terminal.recordedAt,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,state,revisionDigest,dimension){let latest=null,reviewScope=state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0;for(let batch of state.prReviewBaseDispatches??[]){let records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});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:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest,workflowInstanceId:state.workflowInstanceId,workflowRevision:record2.workflowGeneration,baseSha:state.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 path97.join("pr-review",runId,"coverage-disclosure.json")}function derivePrReviewDimensionSettlement(directory,state,revisionDigest){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,revisionDigest),cancellations=state.prReviewDimensionCancellations??{},dispatched=new Set;for(let batch of state.prReviewBaseDispatches??[]){let records=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID});for(let lane of batch.lanes){if(!records.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,state,dimension),latestStructuredUnresolved=latestStructuredReceiptUnresolvedForBaseDimension(directory,state,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}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}}async function readAndVerifyCoverageDisclosure(directory,state){let{prReviewPartialBaseCoverage:record2,prReviewCoverageDisclosurePath:relativePath,prReviewCoverageDisclosureDigest:expectedDigest}=state;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(path97.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(createHash47("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 state=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim());if(!state||state.mode!=="PR_REVIEW"||!state.prHeadSha)throw Error("BLOCKED: partial base coverage requires an active head-bound PR_REVIEW workflow");let normalizedRunId=PrReviewRunIdSchema.parse(runId);if(state.prReviewReservedRunId&&state.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,state),settlement=derivePrReviewDimensionSettlement(directory,state,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"&&!state.prReviewDimensionCancellations?.[entry.dimension])throw Error(`BLOCKED: partial base coverage dimension "${entry.dimension}" declared CANCELLED without a persisted cancellation record`)}let existing=await readAndVerifyCoverageDisclosure(directory,state);if(existing){if(existing.runId===normalizedRunId&&existing.prHeadSha===state.prHeadSha&&existing.revisionDigest===ctx.revisionDigest&&JSON.stringify(existing.unresolvedDimensions)===JSON.stringify(settlement.unresolvedDimensions))return state;throw Error("BLOCKED: partial base coverage admission differs from the immutable existing disclosure")}let record2={schemaVersion:2,runId:normalizedRunId,prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,unresolvedDimensions:settlement.unresolvedDimensions,admittedAt:isoNow()},relativePath=coverageDisclosureRelativePath(normalizedRunId).split(path97.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 fsp6.readFile(absolutePath,"utf8")===raw)await fsp6.rm(absolutePath,{force:!0})}catch{}};try{if(readFileSync36(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=createHash47("sha256").update(raw,"utf8").digest("hex");try{return await writeStateWhileLocked(directory,{...state,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 state=await readPrWorkflowGateStateFromDisk2(directory,sessionID.trim()),record2=state?.prReviewPartialBaseCoverage;if(!state||!record2||record2.runId!==options.runId)return!1;if((state.prReviewArtifactBoundaries??[]).includes(options.boundary))return!1;if(state.prReviewCoverageDisclosurePath!==options.relativePath||state.prReviewCoverageDisclosureDigest!==options.digest)return!1;let absolutePath=validateSwarmPath(directory,options.relativePath);try{let raw=await fsp6.readFile(absolutePath,"utf8");if(createHash47("sha256").update(raw,"utf8").digest("hex")!==options.digest)return!1}catch(error49){if(error49.code!=="ENOENT")throw error49}return await fsp6.rm(absolutePath,{force:!0}),await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewPartialBaseCoverage:void 0,prReviewCoverageDisclosurePath:void 0,prReviewCoverageDisclosureDigest:void 0}),!0})}async function assertPrReviewBaseCoverageSettled(directory,sessionID,gateContext){let state=await requireBoundState(directory,sessionID,"PR_REVIEW");if((state.prReviewBaseDispatches??[]).length===0)throw Error("BLOCKED: PR_REVIEW requires at least one base batch");let ctx=gateContext??await createPrReviewGateContext(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,ctx.revisionDigest);if(settlement.kind==="COMPLETE")return{state,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,state),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===state.prHeadSha&&disclosure.revisionDigest===ctx.revisionDigest&&disclosure.runId===(state.prReviewArtifactRunId??state.prReviewReservedRunId))return{state,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 state=await readPrWorkflowGateStateFromDisk2(directory,normalizeSessionID(sessionID));if(!state||state.mode!=="PR_REVIEW"||!state.prHeadSha)return null;let ctx=await createPrReviewGateContext(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,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_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"},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"]).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 createHash48}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,state,ctx){return requireBoundHelpers2().derivePrReviewCandidateInventory(directory,state,ctx)}function derivePrReviewCriticInventory(directory,state,ctx){return requireBoundHelpers2().derivePrReviewCriticInventory(directory,state,ctx)}function authoritativeReviewerClaims(directory,state,ctx){return requireBoundHelpers2().authoritativeReviewerClaims(directory,state,ctx)}function reviewerSubagentSessionIds(directory,state){return requireBoundHelpers2().reviewerSubagentSessionIds(directory,state)}function prReviewPhaseWindow(state,phase){return requireBoundHelpers2().prReviewPhaseWindow(state,phase)}function batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){return requireBoundHelpers2().batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)}function recordsPassingBatchIntegrity2(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics){return requireBoundHelpers2().recordsPassingBatchIntegrity(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)}function loadArtifactPassingLaneIntegrity(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){return requireBoundHelpers2().loadArtifactPassingLaneIntegrity(directory,state,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,state,phase,ctx,exhaustive=!1){let memoized=phase==="reviewer"?ctx.reviewer:ctx.critic;if(memoized&&!exhaustive)return memoized;let requiredInventory=phase==="reviewer"?derivePrReviewCandidateInventory(directory,state,ctx):derivePrReviewCriticInventory(directory,state,ctx),reviewerClaims=phase==="critic"?authoritativeReviewerClaims(directory,state,ctx):void 0,forbiddenSubagentSessionIds=phase==="critic"?reviewerSubagentSessionIds(directory,state):new Set,expectedMode=`swarm-pr-review:${phase}`,window2=prReviewPhaseWindow(state,phase),requiredSet=new Set(requiredInventory),claims=new Map,contributingBatchIds=[],diagnostics=[],satisfiedObligations=new Set,scannedBatches=[];for(let batch of[...window2].reverse()){if(scannedBatches.push(batch),!batchMayContributeClaims(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx)){appendCompositionDiagnostic(diagnostics,`${phase} batch "${batch.batchId}" was validated against a different inventory or is not wholly successful legacy state; it contributes no claims`);continue}let coherence=state.prReviewBatchCoherence?.[batch.batchId],contributed=!1;for(let qualified of recordsPassingBatchIntegrity2(directory,state,batch.batchId,batch.lanes,expectedMode,batch.validatedAt,!0,forbiddenSubagentSessionIds)){let artifact=loadArtifactPassingLaneIntegrity(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,ctx.revisionDigest);if(!artifact)continue;let declaredItems=qualified.expectedLane.reviewItemIds??[],{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 createHash48("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,state,batchId,laneId,itemIds){let record2=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).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,state){let classifications=new Map;for(let record2 of state.prFeedbackVerifications??[])for(let ownership of record2.ownership){let delegation=findByBatchId(directory,record2.batchId,{parentSessionId:state.sessionID}).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(state,effects=[]){return{status:"applied",state,effects}}function rejected(state,code,detail){return{status:"rejected",state,rejection:{code,detail}}}function currentGeneration(state){return state.revision}function circuitRecordOf(state){let circuit=state.prReviewResilience?.circuit;if(!circuit||!("version"in circuit))return null;return circuit}function withCircuit(state,circuit){if(!state.prReviewResilience)return state;return{...state,prReviewResilience:{...state.prReviewResilience,circuit}}}function reducePrReviewEvent(state,event){switch(event.type){case"base_admission_requested":{let dispatches=state.prReviewBaseDispatches??[];if(dispatches.length>=event.maxBatches)return rejected(state,"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({...state,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:record2},[{kind:"persist_state"}])}case"base_admission_rolled_back":{let dispatches=state.prReviewBaseDispatches??[];if(dispatches.at(-1)?.batchId!==event.batchId)return rejected(state,"rollback_preconditions_failed",`the last admitted base batch is not ${event.batchId}`);if(event.batchDelegationRecordsExist)return rejected(state,"rollback_preconditions_failed",`base batch ${event.batchId} already has delegation records`);let nextDispatches=dispatches.slice(0,-1);return applied({...state,prReviewBaseDispatches:nextDispatches,prReviewBaseDispatch:dispatches.at(-2)},[{kind:"persist_state"}])}case"collection_observed":return applied(state,[{kind:"emit_diagnostic",source:"collection_observer",code:`collection_${event.diagnostic}`,boundedDetail:event.boundedDetail}]);case"lane_structured_result_submitted":{if(event.generation!==currentGeneration(state))return rejected(state,"stale_generation_result",`result generation ${event.generation} does not match the active generation ${currentGeneration(state)}`);if(event.existingReceiptDigest!==void 0){if(event.existingReceiptDigest===event.semanticEnvelopeDigest)return applied(state,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed",replay:!0}]);return rejected(state,"duplicate_conflicting_result",`lane ${event.laneId} already carries a different structured receipt`)}if(event.outcome==="INCOMPLETE")return applied(state);return applied(state,[{kind:"settle_delegation",batchId:event.batchId,laneId:event.laneId,status:"completed"}])}case"circuit_advance_requested":{let adoption=adoptPrReviewCircuit(state.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=state;if(adoption.kind==="migrated")next=withCircuit(state,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(state);if(!circuit||circuit.state!=="HALF_OPEN"||!circuit.probe)return applied(state);if(event.outcome.result==="rolled_back_admission")return applied(withCircuit(state,rollbackPrReviewCircuitProbe(circuit,event.nowMs,event.policy.circuitOpenDurationMs??60000)),[{kind:"persist_state"}]);return applied(state)}case"resilience_config_changed":{if(!event.enabled){if(!state.prReviewResilience)return applied(state);if(state.prReviewResilience.policy.enabled===!1)return applied(state);return applied({...state,prReviewResilience:{...state.prReviewResilience,policy:{...state.prReviewResilience.policy,enabled:!1}}},[{kind:"persist_state"}])}let policy=resolvePrReviewResiliencePolicy(event.policy);return applied({...state,prReviewResilience:{policy,attempts:[],circuit:resetPrReviewResilienceForReEnable({previousCircuit:circuitRecordOf(state),policy,nowMs:event.nowMs})}},[{kind:"persist_state"}])}case"coverage_finalization_requested":{let{settlement}=event;if(settlement.liveDimensions.length>0)return rejected(state,"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(state,"partial_coverage_cannot_approve",`a partial review can never emit ${verdict}`);if(settlement.kind==="NO_COVERAGE"&&verdict!=="INCOMPLETE")return rejected(state,"no_coverage_requires_incomplete",`a zero-coverage review must report INCOMPLETE, not ${verdict}`)}return applied(state)}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(state,"critic_required_unfulfilled",`critic confirmation missing for finding(s): ${unfulfilled.join(", ")}`);return applied(state)}case"armed_recovery_requested":{let reason=bindingRejection(state,event);if(reason)return rejected(state,"stale_foreign_authorization",reason.detail);let cancellations={...state.prReviewDimensionCancellations??{}};for(let dimension of event.dimensionsToCancel)cancellations[dimension]={reason:event.reason,cancelledAt:event.nowIso,source:"armed_recovery"};return applied({...state,prReviewDimensionCancellations:cancellations},[{kind:"persist_state"}])}default:{let exhausted=event;return rejected(state,"unknown_event",`unknown PR-review event discriminant: ${event.type??"(none)"}`)}}}function bindingRejection(state,event){let binding=event.binding;if(binding.sessionID!==state.sessionID)return{detail:`authorization session ${binding.sessionID} is foreign to the active workflow session`};if(binding.workflowInstanceId!==void 0&&state.workflowInstanceId!==void 0&&binding.workflowInstanceId!==state.workflowInstanceId)return{detail:"authorization belongs to a different workflow instance"};if(!state.prHeadSha||binding.prHeadSha!==state.prHeadSha)return{detail:`authorization head ${binding.prHeadSha} does not match the bound head`};if(binding.generation!==currentGeneration(state))return{detail:`authorization generation ${binding.generation} is stale (active: ${currentGeneration(state)})`};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,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,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,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 createHash49,randomUUID as randomUUID17}from"node:crypto";import{readFileSync as readFileSync37,statSync as statSync36}from"node:fs";import*as fsp7 from"node:fs/promises";import*as path98 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(state){let evidence2=JSON.stringify({operations:state.evidence.operations,unmerged_codes:state.evidence.unmergedCodes,paths:state.evidence.paths,paths_truncated:state.evidence.pathsTruncated});return`BLOCKED: PR workflow checkout requires manual Git recovery before activation. code=${state.code} retryable=false required_action=${state.requiredAction} evidence=${evidence2}`}function checkoutRecoveryRecord(state){if(state.kind!=="recovery-required"&&state.kind!=="indeterminate")throw Error("PR workflow checkout recovery requires a terminal Git state");return{code:state.code,retryable:!1,requiredAction:state.requiredAction,evidence:state.evidence,detectedAt:isoNow()}}async function activatePrWorkflow(directory,sessionID,mode,options={}){let normalizedSessionID=normalizeSessionID(sessionID),checkoutPreflight=!await readPrWorkflowGateState(directory,normalizedSessionID)&&options.requireCheckoutPreflight?await _test_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:[path98.join(".swarm",workflowCheckoutMutationLockRelativePath()),path98.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),state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(state)rememberState(directory,state);else forgetTrackedPrWorkflowState(directory,normalizedSessionID);return state}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 preliminary=readDelegations(directory).filter((record3)=>record3.subagentSessionId===child&&record3.correlationId===child&&(record3.mode==="swarm-pr-review:base"||record3.mode==="swarm-pr-review:micro"));if(preliminary.length!==1)return{status:"rejected",reason:`expected one exact child delegation, found ${preliminary.length}`};let parentSessionId=preliminary[0].parentSessionId,record2=preliminary[0];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 state=await readPrWorkflowGateStateFromDisk3(directory,parentSessionId);if(!state||state.mode!=="PR_REVIEW"||!state.workflowInstanceId||!state.prHeadSha||!state.prReviewBaseSha)return{status:"rejected",reason:"no active bound PR_REVIEW workflow"};if((await createPrReviewGateContext2(directory,state)).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!==state.workflowInstanceId)return{status:"rejected",reason:"stale workflow instance binding"};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(state,{type:"lane_structured_result_submitted",batchId,laneId,generation:state.revision,semanticEnvelopeDigest,outcome:parsedResult.data.outcome,...existingReceiptDigest!==void 0?{existingReceiptDigest}:{}});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:child,batchId,laneId,expectedWorkflowInstanceId:state.workflowInstanceId,expectedWorkflowRevision:dispatchWorkflowRevision,expectedBaseSha:state.prReviewBaseSha,receipt:{schemaVersion:1,mode:record2.mode,workflowInstanceId:dispatchWorkflowInstanceId,workflowRevision:dispatchWorkflowRevision,batchId,laneId,workflowLane:record2.workflowLane,ownedWorkflowLanes,baseSha:state.prReviewBaseSha,headSha:state.prHeadSha,dispatchRevisionDigest:input.revisionDigest,childSessionId:child,generation:record2.generation??1,semanticEnvelopeDigest,envelope:parsedResult.data}});if(published.status==="recorded"||published.status==="duplicate")return{status:published.status,receiptDigest:semanticEnvelopeDigest};return{status:"rejected",reason:published.reason}})}async function withPrWorkflowCheckoutPreparationLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (which activates PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (which activates PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*". Run the appropriate command first, then retry checkout preparation.`);if(state.prHeadSha)throw Error(`BLOCKED: ${state.mode} checkout preparation is allowed only before the PR head is bound`);return action(state,{markRecoveryRequired:async(gitState)=>{let nextState={...state,updatedAt:isoNow(),checkoutRecovery:checkoutRecoveryRecord(gitState)},persisted=await writeStateWhileLocked(directory,nextState);return Object.assign(state,persisted),persisted}})}))}async function withInactivePrWorkflowCheckoutRestoreLock(directory,sessionID,action){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,async()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{if(await 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),action()}))}async function assertNoActivePrWorkflowGateForCheckoutRestore(directory){let gateDirectory=validateSwarmPath(directory,WORKFLOW_GATE_DIR),handle;try{handle=await fsp7.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,path98.join(WORKFLOW_GATE_DIR,entry.name)),state=await readPrWorkflowGateStateFileFromDisk(statePath2,entry.name);if(!state)continue;let expectedName=path98.basename(workflowGateStateRelativePath(state.sessionID));if(entry.name!==expectedName)throw Error("BLOCKED: PR workflow gate inventory contains an ambiguous state filename; checkout restoration cannot prove project inactivity");throw Error(`BLOCKED: checkout restoration cannot mutate this project while session "${state.sessionID}" has an active ${state.mode} workflow`)}}catch(error49){scanError=error49}finally{try{await handle.close()}catch(error49){if(error49.code!=="ERR_DIR_CLOSED")closeError=error49}}if(scanError!==void 0)throw scanError;if(closeError!==void 0)throw closeError}async function clearPrWorkflowGateState(directory,sessionID,expectedRevision,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})})}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(`
1254
+ `)){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,tokens=activity?.estimatedTokens??0;if(steps>=watchdog.stall_min_steps||tokens>=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=tokens;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=[];for(let record2 of readDelegations(directory)){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:[]};for(let record2 of readDelegations(directory)){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 state=recovery.state,cancelRevision=null,cancellationObservedRemoteHead;if(options.expectedMode&&state.mode!==options.expectedMode)throw wrongModeError(state,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=state.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(state.mode!=="PR_FEEDBACK"||!state.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(state.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((state.prFeedbackReadyToPublish||recovery.armedShapeUnreadable)&&!options.cancelPublication)throw Error(`BLOCKED: ${state.mode} is armed for publication; abort is blocked. Complete the workflow with complete_pr_workflow (or push the bound commit first) before aborting, 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,state.sessionID,options.laneLiveness),probeRetainedLanes=laneSettlement.probedAliveLaneIds??[],overridesProbeRetention=options.kind==="force"&&laneSettlement.freshOpenLanes===0&&probeRetainedLanes.length>0;if(laneSettlement.openLanes>0&&!overridesProbeRetention){let laneIds=laneSettlement.openLaneIds.filter(Boolean).slice(0,MAX_DISCLOSED_LANE_IDS).join(", ");throw Error(`BLOCKED: ${state.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: ${state.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:state.sessionID,mode:state.mode,kind:options.kind,...state.prHeadSha?{prHeadSha:state.prHeadSha}:{},...state.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??state.revision,{allowSalvagedRead:recovery.salvaged})}catch(error49){try{appendCoreEventSync(directory,{type:"pr_workflow_abort_not_completed",timestamp:isoNow(),sessionID:state.sessionID,mode:state.mode,...state.prHeadSha?{prHeadSha:state.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,state.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.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:state.mode,...state.prHeadSha?{prHeadSha:state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));if(!state)throw noActiveGateError(sessionID);if(request.expectedMode&&state.mode!==request.expectedMode)throw wrongModeError(state,request.expectedMode);let armed=state.prFeedbackReadyToPublish;if(!armed)throw Error(`BLOCKED: ${state.mode} is not armed for publication; armed recovery applies only to an active staged publication authorization (complete or abort normally instead).`);if(request.prHeadSha!==state.prHeadSha)throw Error(`BLOCKED: armed recovery head mismatch: workflow is bound to "${state.prHeadSha??"(none)"}", request declared "${request.prHeadSha}".`);if(state.prReviewBaseSha===void 0!==(request.baseSha===void 0))throw Error(`BLOCKED: armed recovery base mismatch: ${state.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&&state.prReviewBaseSha!==void 0&&request.baseSha!==state.prReviewBaseSha)throw Error(`BLOCKED: armed recovery base mismatch: workflow is merge-base bound to "${state.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!==state.revision)throw Error(`BLOCKED: armed recovery generation mismatch: current gate generation is ${state.revision}, request declared ${request.generation}. Stale requests fail closed; re-read the workflow state and retry.`);if(request.workflowInstanceId===void 0!==(state.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&&state.workflowInstanceId!==void 0&&request.workflowInstanceId!==state.workflowInstanceId)throw Error(`BLOCKED: armed recovery workflow identity mismatch: active workflow is "${state.workflowInstanceId}", request declared "${request.workflowInstanceId}".`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,request.laneLiveness);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=state.prReviewDimensionCancellations;if(state.mode==="PR_REVIEW"&&state.prHeadSha){let ctx=await createPrReviewGateContext2(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,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(state,{type:"armed_recovery_requested",binding:{sessionID:state.sessionID,...state.workflowInstanceId?{workflowInstanceId:state.workflowInstanceId}:{},prHeadSha:state.prHeadSha,revisionDigest:armed.revisionDigest,generation:state.revision},dimensionsToCancel:cancelledDimensions,nowIso:isoNow(),reason:sanitizedReason});if(recoveryOutcome.status==="rejected")throw Error(`BLOCKED: armed recovery rejected (${recoveryOutcome.rejection.code}): ${recoveryOutcome.rejection.detail}`);cancellations=recoveryOutcome.state.prReviewDimensionCancellations??cancellations}}let recoveredAt=isoNow();try{appendCoreEventSync(directory,{type:"pr_workflow_armed_recovery",timestamp:recoveredAt,sessionID:state.sessionID,mode:state.mode,prHeadSha:state.prHeadSha,revisionDigest:armed.revisionDigest,generation:state.revision,settledLanes:laneSettlement.presumedStaleLaneIds?.length??0,cancelledDimensions,reason:sanitizedReason})}catch{}return await writeStateWhileLocked(directory,{...state,updatedAt:recoveredAt,prFeedbackReadyToPublish:void 0,prFeedbackArmedRecovery:{recoveredAt,prHeadSha:state.prHeadSha,revisionDigest:armed.revisionDigest,generation:state.revision,reason:sanitizedReason},...cancellations?{prReviewDimensionCancellations:cancellations}:{}}),{mode:state.mode,prHeadSha:state.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),state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)throw Error(`BLOCKED: no active PR workflow gate for session "${normalizedSessionID}". The gate must be activated before the PR head can be bound.`);if(await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),state.prHeadSha&&state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: active ${state.mode} workflow is bound to PR head "${state.prHeadSha}"; received "${normalizedHead}"`);if(!state.prHeadSha)await assertPrReviewCleanCheckout(directory,state.mode);if(!state.prHeadSha&&state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);if(state.prHeadSha===normalizedHead){if(state.mode==="PR_FEEDBACK")await assertPrFeedbackTrackingCheckout(directory,normalizedHead);return state}let nextState={...state,prHeadSha:normalizedHead,checkoutRecovery:void 0,updatedAt:isoNow()};await _test_exports2.beforePrFeedbackTrackingPersist?.();try{return await writeStateWhileLocked(directory,nextState)}catch(error49){if(!state.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 state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK rebind is refused while publication is armed; complete the workflow (or push the bound commit) before rebinding.");let openLanes=readDelegations(directory).filter((record2)=>record2.parentSessionId===state.sessionID&&record2.mode?.startsWith("swarm-pr-")&&(record2.status==="pending"||record2.status==="running"));if(openLanes.length>0)throw Error(`BLOCKED: PR_FEEDBACK rebind refused while ${openLanes.length} PR workflow lane(s) are still in flight; collect their results first.`);if(normalizedHead===state.prHeadSha)throw Error(`BLOCKED: PR_FEEDBACK rebind to the current intake head "${normalizedHead}" is a no-op; a rebind must move to a genuinely new verified PR head after merge/rebase repair.`);await assertCurrentCheckoutHead(directory,normalizedHead,state.mode),await assertPrFeedbackTrackingCheckout(directory,normalizedHead);let nextState={...state,prHeadSha:normalizedHead,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackRebindCount:(state.prFeedbackRebindCount??0)+1,updatedAt:isoNow()};try{appendCoreEventSync(directory,{type:"pr_feedback_rebound",timestamp:isoNow(),sessionID:state.sessionID,previousPrHeadSha:state.prHeadSha,prHeadSha:normalizedHead,rebindCount:nextState.prFeedbackRebindCount})}catch{}return withSessionStateMutation(directory,state.sessionID,async()=>writeStateWhileLocked(directory,nextState))}async function bindPrReviewBase(directory,sessionID,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw Error("BLOCKED: only PR_REVIEW can bind a review merge base");let baseRef=options.baseRef.trim(),baseSha=normalizePrHeadSha(options.baseSha).toLowerCase();if(!baseRef)throw Error("BLOCKED: PR_REVIEW base_ref must not be empty");if(state.prReviewBaseRef&&state.prReviewBaseRef!==baseRef||state.prReviewBaseSha&&state.prReviewBaseSha!==baseSha)throw Error(`BLOCKED: active PR_REVIEW is bound to merge-base scope "${state.prReviewBaseRef??"(unbound)"}" at "${state.prReviewBaseSha??"(unbound)"}"; received "${baseRef}" at "${baseSha}"`);if(state.prReviewBaseRef===baseRef&&state.prReviewBaseSha===baseSha)return state;let prHeadSha=normalizePrHeadSha(options.prHeadSha).toLowerCase(),diffStats=await _test_exports2.resolvePrReviewDiffStatsAsync(directory,baseSha,prHeadSha);return state={...state,prReviewBaseRef:baseRef,prReviewBaseSha:baseSha,prReviewDepthTier:computePrReviewDepthTier(diffStats),...diffStats?{prReviewDiffStats:diffStats}:{},updatedAt:isoNow()},await persistState2(directory,state),state}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 state=await readPrWorkflowGateState(directory,sessionID);if(!state)return null;if(toolName===DISPATCH_TOOL_NAME)return state;if(toolName===BLOCKING_DISPATCH_TOOL_NAME)throw Error(`BLOCKED: active ${state.mode} workflow for session "${state.sessionID}" requires ${DISPATCH_TOOL_NAME}; ${BLOCKING_DISPATCH_TOOL_NAME} is not allowed`);return state}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 batchLaneRecords(directory,state,batchId,laneId){return findByBatchId(directory,batchId,{parentSessionId:state.sessionID}).filter((record2)=>record2.laneId===laneId)}function batchIsTerminal(directory,state,batchId){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID});return records.length>0&&records.every((record2)=>TERMINAL_FAILED_DELEGATION_STATUSES2.has(record2.status)||record2.status==="consumed")}function effectivePrReviewResiliencePolicy(state,requestedPolicy){return state.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,state){let signals=[];for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes){let latest=latestDelegationRecord(batchLaneRecords(directory,state,batch.batchId,lane.laneId));if(!latest)continue;let signal=classifyPrReviewCircuitSignal(latest);if(signal)signals.push(signal)}return signals}function probeObservationForCircuit(directory,state,circuit){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return;let latest=latestDelegationRecord(batchLaneRecords(directory,state,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,state=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},state=await writeStateWhileLocked(directory,{...state,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(state,{type:"circuit_advance_requested",nowMs:nowMs3,laneSignals:laneSignalsForCircuitReview(directory,state),probeObservation:circuit?.state==="HALF_OPEN"?probeObservationForCircuit(directory,state,circuit):void 0,admission:args2.admission,policy:snapshot.policy});if(advanceOutcome.status==="rejected")return{state,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},state=await writeStateWhileLocked(directory,{...nextState,updatedAt:isoNow(),prReviewResilience:snapshot});else state=nextState;if(blockedReason!==void 0)return{state,snapshot,blocked:{reason:blockedReason}};let pendingProbe=nextState.prReviewResilience?.circuit;if(pendingProbe&&"version"in pendingProbe&&pendingProbe.state==="HALF_OPEN"&&pendingProbe.probe)return{state,snapshot,pendingProbeCircuit:pendingProbe};return{state,snapshot}}async function preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,policy,liveResilienceEnabled){let nextState=state,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(),status=session?.status;if(!session||typeof status!=="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()=>status.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,state,attempt,revisionDigest,policy){let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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,state,attempt.fanoutBatchId):!1};let canaryRecords=batchLaneRecords(directory,state,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 state=await bindPrWorkflowHeadWhileLocked(directory,normalizedSessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"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((state.prReviewDepthTier??"L")==="L"&&normalizedLanes.some((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1)){let rejection=await tierLConsolidationRejection(directory,state,normalizedLanes,options.revisionDigest);if(rejection)throw Error(`BLOCKED: PR_REVIEW base dispatch at depth tier L requires one dedicated lane per dimension; consolidated owned_workflow_lanes are allowed only at tiers S and M, or on a retry batch that satisfies all five of: (1) every consolidated dimension already has a recorded lane that reached a terminal non-successful state; (2) no consolidated dimension already has a successful source; (3) no single lane owns all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions; (4) a batch claiming all ${PR_REVIEW_BASE_DIMENSION_IDS.length} dimensions uses at least ${PR_REVIEW_BASE_LANE_FLOORS.L} lanes; and (5) across every recorded base batch the six dimensions stay backed by at least ${PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR} distinct lanes, counting each dimension no consolidated lane claims as one plus the FEWEST declared consolidated lanes that suffice to cover every dimension consolidated lanes do claim. Clause 5 is cumulative over every base batch this wave recorded, including batches the `+"capacity GC has since dropped, and it counts a minimum cover rather than declarations — so "+"neither splitting one consolidation across several batches nor declaring overlapping or duplicate consolidations evades it. "+rejection)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewBaseDispatches??[];if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW base batch id "${batchId}" is already recorded`);let depthTier=state.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(state,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,previous}=await preflightPrReviewResilienceCircuitBeforePrune(directory,state,previous,resiliencePolicy,liveResilienceEnabled));if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,options.revisionDigest),previous=state.prReviewBaseDispatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW base batch limit reached")}let nextResilience=state.prReviewResilience;if(!nextResilience){if(nextResilience={policy:resiliencePolicy,attempts:[]},previous.length>0)state=await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prReviewResilience:nextResilience}),previous=state.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(state,configEvent);if(outcome.status==="applied"&&outcome.effects.some((effect)=>effect.kind==="persist_state"))state=await writeStateWhileLocked(directory,{...outcome.state,updatedAt:isoNow()}),previous=state.prReviewBaseDispatches??[],nextResilience=state.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,state)).revisionDigest;let snapshot=nextResilience??{policy:resiliencePolicy,attempts:[]},pendingProbeCircuit;if(liveResilienceEnabled){let outcome=await advanceResilienceCircuitWhileLocked({directory,state,snapshot,admission:{batchId,laneId:normalizedLanes[0]?.laneId??""}});if(state=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,state,revisionDigest);globalInFlight=PR_REVIEW_BASE_DIMENSION_IDS.filter((dimension)=>globalAttempts.inFlight.has(dimension));let globalTarget=unresolvedPrReviewBaseDimensions(globalAttempts),evaluated=await evaluatePrReviewResilienceAttempt(directory,state,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,state,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,state,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,state,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,state)).revisionDigest,attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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(state,{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:[...state.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 state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_REVIEW")return!1;let batchRecords=findByBatchId(directory,normalizedBatchId,{parentSessionId:normalizedSessionID}),rollbackOutcome=reducePrReviewEvent(state,{type:"base_admission_rolled_back",batchId:normalizedBatchId,batchDelegationRecordsExist:batchRecords.length>0});if(rollbackOutcome.status==="rejected")return!1;let rollbackState=rollbackOutcome.state,currentBaseDispatches=state.prReviewBaseDispatches??[],nextBaseDispatches=rollbackState.prReviewBaseDispatches??[],rolledBackDimensions=new Set(currentBaseDispatches.at(-1)?.lanes.flatMap((lane)=>lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane])??[]),nextContractRetryDimensions=contractRetry?(state.prReviewContractRetryDimensions??[]).filter((dimension)=>!rolledBackDimensions.has(dimension)):state.prReviewContractRetryDimensions,lastAttempt=state.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,{...state,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(state,normalizedLanes,dedicatedSuccessful){let consolidatedDimensions=new Set,consolidatedSets=[],consider=(owned,allowSupersede)=>{let declared=owned.filter((dimension)=>Boolean(dimension));if(declared.length<2)return;let live=allowSupersede?declared.filter((dimension)=>!dedicatedSuccessful.has(dimension)):declared;if(live.length===0)return;consolidatedSets.push([...new Set(live)]);for(let dimension of live)consolidatedDimensions.add(dimension)},considerLane=(lane,allowSupersede)=>consider(lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane],allowSupersede);for(let batch of state.prReviewBaseDispatches??[])for(let lane of batch.lanes)considerLane(lane,!0);for(let key2 of state.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,state,normalizedLanes,revisionDigest){if((state.prReviewBaseDispatches?.length??0)===0)return"This is the initial base wave, which may never consolidate at tier L.";let dimensionCount=PR_REVIEW_BASE_DIMENSION_IDS.length,consolidatedLanes=normalizedLanes.filter((lane)=>(lane.ownedWorkflowLanes?.length??1)!==1),wholeWaveLane=consolidatedLanes.find((lane)=>(lane.ownedWorkflowLanes?.length??1)>=dimensionCount);if(wholeWaveLane)return`Lane "${wholeWaveLane.laneId}" owns all ${dimensionCount} dimensions on its own.`;if(new Set(normalizedLanes.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane])).size>=dimensionCount&&normalizedLanes.length<PR_REVIEW_BASE_LANE_FLOORS.L)return`This batch claims all ${dimensionCount} dimensions with only ${normalizedLanes.length} lanes.`;let digest3=revisionDigest;if(!digest3)digest3=(await createPrReviewGateContext2(directory,state)).revisionDigest;let attempts=summarizePrReviewBaseDimensionAttempts(directory,state,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(state,normalizedLanes,attempts.dedicatedSuccessful);if(backing.backingLanes<PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR)return`Across every base batch this wave would be backed by only ${backing.backingLanes} distinct lanes (each dimension no consolidated lane claims counts as one, plus the fewest declared consolidated lanes that cover the rest), and dimensions ${backing.consolidatedDimensions.join(", ")} would be covered by consolidated lanes.`;return null}async function prunePrWorkflowBatchesForCapacity(directory,state,revisionDigest){try{let digest3=revisionDigest??(await createPrReviewGateContext2(directory,state)).revisionDigest,before={candidate:derivePrReviewCandidateInventory2(directory,state,{revisionDigest:digest3}),critic:derivePrReviewCriticInventory2(directory,state,{revisionDigest:digest3})},pruned=pruneWorkflowBatches(directory,state,digest3);if(!pruned)return state;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"),state;let survivingBaseIds=new Set((pruned.prReviewBaseDispatches??[]).map((batch)=>batch.batchId));if(state.prReviewBaseDispatch&&!survivingBaseIds.has(state.prReviewBaseDispatch.batchId))return warn("PR_REVIEW batch GC aborted: the latest base dispatch pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_REVIEW batch GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}function pruneWorkflowBatches(directory,state,revisionDigest){let baseBatches=state.prReviewBaseDispatches??[],validationBatches=state.prReviewValidationBatches??[],ctx={revisionDigest},contributingBaseBatchIds=new Set;for(let batch of baseBatches){let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,revisionDigest);if(batch.lanes.some((lane)=>((lane.ownedWorkflowLanes?.length)?lane.ownedWorkflowLanes:[lane.workflowLane]).every((dimension)=>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,state,"reviewer",ctx,!0).contributingBatchIds),survivingValidation=validationBatches.filter((batch)=>{if(batch.phase==="council"||batch.phase==="critic")return!0;if(newestBatchIdByPhase.get(batch.phase)===batch.batchId)return!0;return contributingReviewerBatchIds.has(batch.batchId)});if(survivingBase.length===baseBatches.length&&survivingValidation.length===validationBatches.length)return null;let survivingValidationIds=new Set(survivingValidation.map((batch)=>batch.batchId)),retiredReviewerSessionIds=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let batch of validationBatches){if(batch.phase!=="reviewer")continue;if(survivingValidationIds.has(batch.batchId))continue;for(let record2 of findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)retiredReviewerSessionIds.add(subagentSessionId)}}if(retiredReviewerSessionIds.size>MAX_RETIRED_REVIEWER_SESSION_IDS)return warn("PR_REVIEW batch GC aborted: retiring these reviewer batches would overflow the forbidden child-session ledger; every batch was kept"),null;let survivingBaseIds=new Set(survivingBase.map((batch)=>batch.batchId)),retiredConsolidatedLanes=new Set(state.prReviewRetiredConsolidatedLanes??[]);for(let batch of baseBatches){if(survivingBaseIds.has(batch.batchId))continue;for(let lane of batch.lanes){let owned=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(new Set(owned).size<2)continue;retiredConsolidatedLanes.add(encodeConsolidatedLaneKey(owned))}}if(retiredConsolidatedLanes.size>MAX_RETIRED_CONSOLIDATED_LANES)return warn("PR_REVIEW batch GC aborted: retiring these base batches would overflow the retired consolidated-lane ledger; every batch was kept"),null;let survivingBatchIds=new Set([...survivingBaseIds,...survivingValidationIds]),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([batchId])=>survivingBatchIds.has(batchId)));return{...state,...state.prReviewBaseDispatches?{prReviewBaseDispatches:survivingBase}:{},...state.prReviewValidationBatches?{prReviewValidationBatches:survivingValidation}:{},prReviewBatchCoherence:Object.keys(coherence).length>0?coherence:void 0,prReviewRetiredReviewerSessionIds:retiredReviewerSessionIds.size>0?[...retiredReviewerSessionIds]:void 0,prReviewRetiredConsolidatedLanes:retiredConsolidatedLanes.size>0?[...retiredConsolidatedLanes]:void 0}}async function 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 state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_REVIEW")throw wrongModeError(state,"PR_REVIEW");if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW validation dispatch requires a completed trigger evaluation");let ctx=await createPrReviewGateContext2(directory,state);if(phase==="reviewer"&&(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))state=await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);else if(phase==="critic")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);ctx={revisionDigest:ctx.revisionDigest};let normalizedLanes=normalizeWorkflowLanes(lanes);if((phase==="reviewer"||phase==="critic")&&normalizedLanes.some((lane)=>!lane.reviewItemIds?.length))throw Error(`BLOCKED: PR_REVIEW ${phase} lanes require non-empty review_item_ids ownership`);let validatedInventory;if(phase==="reviewer"||phase==="critic"){assertNoDuplicates(normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]),`PR_REVIEW ${phase} review item ownership`);let assigned=normalizedLanes.flatMap((lane)=>lane.reviewItemIds??[]);validatedInventory=phase==="reviewer"?derivePrReviewCandidateInventory2(directory,state,ctx):derivePrReviewCriticInventory2(directory,state,ctx),assertStringSetSubset(assigned,validatedInventory,`PR_REVIEW ${phase} ownership`)}let batchId=normalizeBatchId(options.batchId),previous=state.prReviewValidationBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_REVIEW validation batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrWorkflowBatchesForCapacity(directory,state,ctx.revisionDigest),previous=state.prReviewValidationBatches??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_REVIEW validation batch limit reached")}let record2={batchId,phase,lanes:normalizedLanes,validatedAt:isoNow()},reviewerItemBindings=phase==="critic"?criticReviewerItemBindings(directory,state,normalizedLanes,ctx):void 0,retained=phase==="reviewer"?previous.filter((batch)=>batch.phase!=="critic"||Boolean(state.prReviewBatchCoherence?.[batch.batchId]?.reviewerItemBindings)):previous,retainedIds=new Set(retained.map((batch)=>batch.batchId)),coherence=Object.fromEntries(Object.entries(state.prReviewBatchCoherence??{}).filter(([id])=>retainedIds.has(id)));if(validatedInventory)coherence[batchId]={validatedInventory,...reviewerItemBindings?{reviewerItemBindings,reviewerItemBindingKeyEncoding:"prefixed-v1"}:{}};let nextState={...state,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 state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=gateContext??await createPrReviewGateContext2(directory,state),declaredPhases=new Set((state.prReviewValidationBatches??[]).map((batch)=>batch.phase)),phases=phase?[phase]:["council","reviewer","critic"].filter((candidate)=>declaredPhases.has(candidate));for(let requiredPhase of phases){let validationBatches=state.prReviewValidationBatches??[],batches=requiredPhase==="council"?validationBatches.filter((batch)=>batch.phase==="council"):prReviewPhaseWindow2(state,requiredPhase);if(batches.length===0)throw Error(requiredPhase==="reviewer"&&declaredPhases.has("council")?"BLOCKED: PR_REVIEW requires at least one reviewer batch after the latest council batch":`BLOCKED: PR_REVIEW requires at least one ${requiredPhase} batch`);if(requiredPhase==="council"){let settled=new Set;for(let batch of batches)for(let obligation of successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest))settled.add(obligation);let missing=[...new Set(batches.flatMap((batch)=>batch.lanes.map((lane)=>lane.workflowLane)))].filter((obligation)=>!settled.has(obligation));if(missing.length>0)throw Error(`BLOCKED: PR_REVIEW council obligations lack successful exact artifacts: ${missing.join(", ")}`);continue}let composed=composePrReviewPhaseVerdicts(directory,state,requiredPhase,ctx);if(composed.unclaimed.length>0){let named=composed.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=composed.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW ${requiredPhase} items lack an authenticated verdict from any successful lane: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:"")+(composed.diagnostics.length>0?`; diagnostics: ${composed.diagnostics.join(" | ")}`:""))}if(assertSettledPhaseHasAuthoritativeVerdicts(requiredPhase,composed,requiredPhase==="reviewer"?deriveLatestPrReviewReviewerVerdicts(directory,state,ctx):deriveLatestPrReviewCriticVerdicts(directory,state,ctx),`assertPrReviewValidationSettled(${requiredPhase})`),composed.diagnostics.length>0)warn(`PR_REVIEW ${requiredPhase} settled by composition across batches [${composed.contributingBatchIds.join(", ")}] with abandoned or ineligible lanes`,composed.diagnostics)}return state}async function declarePrFeedbackInventory(directory,sessionID,inventoryIds,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let normalizedInventory=normalizeInventoryIds(inventoryIds),requiredHandoffIds=state.prFeedbackReviewHandoff?.findingIds??[],inventorySet=new Set(normalizedInventory),missingHandoffIds=requiredHandoffIds.filter((findingId)=>!inventorySet.has(findingId));if(missingHandoffIds.length>0)throw Error(`BLOCKED: PR_FEEDBACK inventory must include every continued review finding: ${missingHandoffIds.join(", ")}`);if(state.prFeedbackInventory){let existing=state.prFeedbackInventory;if(sameStringArray(existing,normalizedInventory))return state;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=state.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={...state,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={...state,updatedAt:isoNow(),prFeedbackInventory:normalizedInventory,prFeedbackVerifications:[]};return await persistState2(directory,nextState),nextState}async function prunePrFeedbackVerificationsForCapacity(directory,state){try{let digest3=await currentPrFeedbackRevisionDigest(directory,state),batches=state.prFeedbackVerifications??[],before=prFeedbackCoveredItems(directory,state,digest3),newestBatchId=batches.at(-1)?.batchId,surviving=batches.filter((batch)=>batch.batchId===newestBatchId||prFeedbackBatchCoveredItems(directory,state,batch,digest3).size>0);if(surviving.length===batches.length)return state;let retiredItemOwnership={...state.prFeedbackRetiredItemOwnership??{}},survivingIds=new Set(surviving.map((batch)=>batch.batchId));for(let batch of batches){if(survivingIds.has(batch.batchId))continue;for(let lane of batch.ownership)for(let itemId of lane.ownedItemIds)retiredItemOwnership[itemId]=lane.laneId}if(Object.keys(retiredItemOwnership).length>MAX_RETIRED_FEEDBACK_ITEM_OWNERS)return warn("PR_FEEDBACK verification GC aborted: retiring these batches would overflow the item-ownership ledger; every batch was kept"),state;let pruned={...state,prFeedbackVerifications:surviving,prFeedbackRetiredItemOwnership:Object.keys(retiredItemOwnership).length>0?retiredItemOwnership:void 0},after=prFeedbackCoveredItems(directory,pruned,digest3);if(!sameStringSet([...before],[...after]))return warn("PR_FEEDBACK verification GC aborted: pruning would have changed the covered inventory; every batch was kept"),state;if(state.prFeedbackVerification&&!survivingIds.has(state.prFeedbackVerification.batchId))return warn("PR_FEEDBACK verification GC aborted: the latest verification pointer would have been orphaned"),state;return pruned}catch(error49){return warn(`PR_FEEDBACK verification GC aborted: ${error49 instanceof Error?error49.message:String(error49)}`),state}}async function enforcePrFeedbackVerificationOwnership(directory,sessionID,ownership,options){let state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory||inventory.length===0)throw Error(`BLOCKED: PR_FEEDBACK verification for session "${state.sessionID}" requires a declared feedback inventory before dispatch`);let normalizedOwnership=normalizeOwnership(ownership),inventorySet=new Set(inventory),claimedByItemId=new Map,previous=state.prFeedbackVerifications??[],batchId=normalizeBatchId(options.batchId);if(previous.some((record3)=>record3.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK verification batch id "${batchId}" is already recorded`);if(previous.length>=MAX_WORKFLOW_BATCHES){if(state=await prunePrFeedbackVerificationsForCapacity(directory,state),previous=state.prFeedbackVerifications??[],previous.length>=MAX_WORKFLOW_BATCHES)throw Error("BLOCKED: PR_FEEDBACK verification batch limit reached")}for(let[itemId,laneId]of Object.entries(state.prFeedbackRetiredItemOwnership??{}))claimedByItemId.set(itemId,laneId);for(let record3 of previous)for(let lane of record3.ownership)for(let itemId of lane.ownedItemIds)claimedByItemId.set(itemId,lane.laneId);for(let lane of normalizedOwnership)for(let itemId of lane.ownedItemIds){if(!inventorySet.has(itemId))throw Error(`BLOCKED: PR_FEEDBACK verification lane "${lane.laneId}" owns undeclared item "${itemId}"`);let previousLane=claimedByItemId.get(itemId);if(previousLane&&previousLane!==lane.laneId)throw Error(`BLOCKED: PR_FEEDBACK verification item "${itemId}" is owned by both "${previousLane}" and "${lane.laneId}"`);claimedByItemId.set(itemId,lane.laneId)}let record2={batchId,ownership:normalizedOwnership,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackVerifications:[...previous,record2],prFeedbackVerification:record2};return await persistState2(directory,nextState),nextState}function prFeedbackBatchCoveredItems(directory,state,batch,currentDigest){let covered=new Set,successfulLaneIds=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.ownership.map((lane)=>({laneId:lane.laneId,workflowLane:lane.laneId})),"swarm-pr-feedback:verification",batch.validatedAt,!1,new Set,currentDigest);for(let lane of batch.ownership){if(!successfulLaneIds.has(lane.laneId))continue;if(!legacyFeedbackArtifactCoversItems(directory,state,batch.batchId,lane.laneId,lane.ownedItemIds))continue;for(let itemId of lane.ownedItemIds)covered.add(itemId)}return covered}function prFeedbackCoveredItems(directory,state,currentDigest){let covered=new Set;for(let batch of state.prFeedbackVerifications??[])for(let itemId of prFeedbackBatchCoveredItems(directory,state,batch,currentDigest))covered.add(itemId);return covered}async function assertPrFeedbackVerificationSettledState(directory,state){if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let currentDigest=await currentPrFeedbackRevisionDigest(directory,state),inventory=state.prFeedbackInventory,batches=state.prFeedbackVerifications??[];if(!inventory||batches.length===0)throw Error("BLOCKED: PR_FEEDBACK requires an immutable inventory and verification batches");let covered=prFeedbackCoveredItems(directory,state,currentDigest),missing=inventory.filter((itemId)=>!covered.has(itemId));if(missing.length>0||covered.size!==inventory.length)throw Error(`BLOCKED: PR_FEEDBACK verification ownership is incomplete; missing inventory items: ${missing.join(", ")||"(none)"}`);return currentDigest}async function assertPrFeedbackVerificationSettled(directory,sessionID){let state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK");return await assertPrFeedbackVerificationSettledState(directory,state),state}async function recordPrFeedbackStageA(directory,sessionID,revisionDigest,checks3,options={}){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK Stage A receipt is stale because the working-tree revision changed during validation");if(checks3.length<2||checks3.length>258)throw Error("BLOCKED: PR_FEEDBACK Stage A requires two to 258 controller-created check receipts");let optionalCategoryOrder=["build","typecheck","lint"],applicableCategories=options.applicableCategories??optionalCategoryOrder.filter((category)=>checks3.some((check2)=>check2.category===category));if(assertNoDuplicates(applicableCategories,"PR_FEEDBACK Stage A applicable categories"),applicableCategories.some((category)=>!optionalCategoryOrder.includes(category)))throw Error("BLOCKED: PR_FEEDBACK Stage A applicability may contain only build, typecheck, and lint");let required2=new Set(["diff-check","reproduction",...applicableCategories]),singletonSeen=new Set,applicableObligations=[...options.applicableObligations??[]];assertNoDuplicates(applicableObligations.map(({id})=>id),"PR_FEEDBACK Stage A applicable obligations");let requiredObligationIds=new Set(applicableObligations.map(({id})=>id)),commandDigests=new Set,reproductionFeedbackItemIds=[];for(let check2 of checks3){if(["diff-check","reproduction"].includes(check2.category)&&singletonSeen.has(check2.category))throw Error(`BLOCKED: PR_FEEDBACK Stage A contains duplicate category "${check2.category}"`);if(singletonSeen.add(check2.category),required2.delete(check2.category),check2.obligationId){let obligation=applicableObligations.find((candidate)=>candidate.id===check2.obligationId);if(!obligation||obligation.category!==check2.category||obligation.workingDirectory!==(check2.workingDirectory??".")||!requiredObligationIds.delete(check2.obligationId))throw Error(`BLOCKED: PR_FEEDBACK Stage A receipt does not match one exact applicable obligation: ${check2.obligationId}`);let sourceContract=obligation.source.includes(".pr-validation.json#")?{path:obligation.source.slice(0,obligation.source.lastIndexOf("#")),id:obligation.source.slice(obligation.source.lastIndexOf("#")+1)}:void 0,requiredContract=obligation.validatorContract??sourceContract;if(requiredContract&&(check2.validatorContract?.path!==requiredContract.path||check2.validatorContract.id!==requiredContract.id))throw Error(`BLOCKED: PR_FEEDBACK Stage A obligation ${obligation.id} requires exact validator contract provenance`)}let commandDigest=createHash49("sha256").update(`${check2.obligationId??check2.category}\x00${check2.workingDirectory??"."}\x00${check2.command.join("\x00")}`).digest("hex");if(commandDigests.has(commandDigest))throw Error("BLOCKED: PR_FEEDBACK Stage A cannot reuse one command as multiple check receipts");if(commandDigests.add(commandDigest),check2.category==="diff-check"&&!sameStringArray(check2.command,["git","diff","--check"]))throw Error("BLOCKED: PR_FEEDBACK Stage A diff-check receipt is not the exact git diff --check command");if(check2.category==="reproduction"&&(!check2.targets?.length||!check2.feedbackTargets?.length||check2.targets.some((target)=>!check2.command.join(" ").includes(target))))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction receipt requires exact selected targets");if(check2.category==="reproduction"){if(reproductionFeedbackItemIds=check2.feedbackTargets.map((mapping)=>mapping.feedbackItemId),assertNoDuplicates(reproductionFeedbackItemIds,"PR_FEEDBACK Stage A reproduction feedback item mappings"),check2.feedbackTargets.some((mapping)=>!check2.targets.includes(mapping.target)))throw Error("BLOCKED: PR_FEEDBACK Stage A feedback mappings must reference exact executed reproduction targets")}}if(required2.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing required checks: ${[...required2].join(", ")}`);if(requiredObligationIds.size>0)throw Error(`BLOCKED: PR_FEEDBACK Stage A is missing applicable workspace obligations: ${[...requiredObligationIds].join(", ")}`);if(!sameStringArray(reproductionFeedbackItemIds,state.prFeedbackInventory??[]))throw Error("BLOCKED: PR_FEEDBACK Stage A reproduction must map every immutable feedback item exactly once and in declared order");let normalizedCategories=optionalCategoryOrder.filter((category)=>applicableCategories.includes(category)),retainsGateBatches=stageARetainsGateBatches(state.prFeedbackStageA,{revisionDigest:currentDigest,applicableCategories:normalizedCategories,applicableObligations}),nextState={...state,updatedAt:isoNow(),prFeedbackStageA:{revisionDigest:currentDigest,checks:[...checks3],feedbackItemIds:reproductionFeedbackItemIds,applicableCategories:normalizedCategories,applicableObligations,validatedAt:isoNow()},prFeedbackGateBatches:retainsGateBatches?[...state.prFeedbackGateBatches??[]]:[],prFeedbackReadyToPublish:void 0},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 state=await bindPrWorkflowHead(directory,sessionID,options.prHeadSha);if(state.mode!=="PR_FEEDBACK")throw wrongModeError(state,"PR_FEEDBACK");let inventory=state.prFeedbackInventory;if(!inventory?.length)throw Error("BLOCKED: PR_FEEDBACK ordered gates require an immutable feedback inventory");let normalized=normalizeOwnership([lane])[0];if(!sameStringArray(normalized.ownedItemIds,inventory))throw Error(`BLOCKED: PR_FEEDBACK ${phase} must own every inventory item exactly once and in declared order`);let phaseIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(phase),prerequisite=PR_FEEDBACK_PHASE_ORDER[phaseIndex-1];if(prerequisite)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,prerequisite);let{prFeedbackStageA:stageA,prFeedbackInventory:refreshedInventory}=state,currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(!stageA||!refreshedInventory||stageA.revisionDigest!==currentDigest||!sameStringArray(stageA.feedbackItemIds??[],refreshedInventory)||options.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires fresh Stage A checks on the current revision`);let batchId=normalizeBatchId(options.batchId),previous=state.prFeedbackGateBatches??[];if(previous.some((batch)=>batch.batchId===batchId))throw Error(`BLOCKED: PR_FEEDBACK gate batch id "${batchId}" is already recorded`);let retained=previous.filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<phaseIndex),record2={batchId,phase,laneId:normalized.laneId,itemIds:normalized.ownedItemIds,revisionDigest:currentDigest,validatedAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackGateBatches:[...retained,record2]};return await persistState2(directory,nextState),nextState}async function assertPrFeedbackGatePhaseSettled(directory,sessionID,phase){let state=await requireBoundState2(directory,sessionID,"PR_FEEDBACK"),currentDigest=await currentPrFeedbackRevisionDigest(directory,state);if(state.prFeedbackStageA?.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} cannot use stale Stage A evidence`);if(!sameStringArray(state.prFeedbackStageA?.feedbackItemIds??[],state.prFeedbackInventory??[]))throw Error(`BLOCKED: PR_FEEDBACK ${phase} Stage A reproduction is not bound to the exact immutable feedback inventory`);let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===phase);if(!batch||batch.revisionDigest!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} has no validation batch on the current revision`);if(!sameStringArray(batch.itemIds,state.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,state,batch.batchId,[{laneId:batch.laneId,workflowLane:phase,reviewItemIds:batch.itemIds}],`swarm-pr-feedback:${phase}`,batch.validatedAt,!0,new Set,currentDigest).has(phase))throw Error(`BLOCKED: PR_FEEDBACK ${phase} requires one complete, non-degraded positive verdict row per inventory item`);if(findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).find((candidate)=>candidate.laneId===batch.laneId)?.workspace?.dirtyHash!==currentDigest)throw Error(`BLOCKED: PR_FEEDBACK ${phase} artifact is not bound to the current revision digest`);return assertIndependentFeedbackGateSessions(directory,state,phase),state}function assertIndependentFeedbackGateSessions(directory,state,throughPhase){let throughIndex=PR_FEEDBACK_PHASE_ORDER.indexOf(throughPhase),batches=(state.prFeedbackGateBatches??[]).filter((batch)=>PR_FEEDBACK_PHASE_ORDER.indexOf(batch.phase)<=throughIndex),seenSessions=new Set;for(let batch of batches){let matching=findByBatchId(directory,batch.batchId,{parentSessionId:state.sessionID}).filter((record3)=>record3.laneId===batch.laneId);if(matching.length!==1)throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} must resolve from exactly one durable child session`);let record2=matching[0],expectedRole=PR_FEEDBACK_PHASE_ROLE[batch.phase];if(!(record2.normalizedAgent===expectedRole||expectedRole==="critic"&&record2.normalizedAgent.startsWith("critic_")))throw Error(`BLOCKED: PR_FEEDBACK ${batch.phase} requires role ${expectedRole}, received ${record2.normalizedAgent||"(unknown)"}`);if(seenSessions.has(record2.subagentSessionId))throw Error(`BLOCKED: PR_FEEDBACK independent phases reused child session "${record2.subagentSessionId}"`);seenSessions.add(record2.subagentSessionId)}}async function assertPrFeedbackReadyToPublish(directory,sessionID){let state=await assertPrFeedbackVerificationSettled(directory,sessionID);for(let phase of PR_FEEDBACK_PHASE_ORDER)state=await assertPrFeedbackGatePhaseSettled(directory,sessionID,phase);return state}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,state,active,component){switch(component){case"digest":try{let digest3=await currentPrFeedbackRevisionDigest(directory,state);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(state,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,state,active){for(let component of PUBLICATION_IDENTITY_COMPONENTS){let check2=await verifyPublicationIdentityComponent(directory,state,active,component);if(check2.kind!=="intact")return check2}if(!publicationEvidenceJoinIntact(state,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(state,active){if(state.prFeedbackStageA?.validatedAt!==active.evidence.stageAValidatedAt)return!1;for(let join76 of active.evidence.batches){let batch=[...state.prFeedbackGateBatches??[]].reverse().find((candidate)=>candidate.phase===join76.phase);if(!batch||batch.batchId!==join76.batchId||batch.laneId!==join76.laneId)return!1}return!0}function buildPublicationEvidenceJoin(state,currentDigest){let stageA=state.prFeedbackStageA;if(!stageA||stageA.revisionDigest!==currentDigest||!stageA.validatedAt)return null;let batches=[];for(let phase of PR_FEEDBACK_PHASE_ORDER){let batch=[...state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")throw Error("BLOCKED: PR_FEEDBACK publication invalidation requires an active PR_FEEDBACK gate");return applyPublicationInvalidationWhileLocked(directory,state,reason,options)})}async function applyPublicationInvalidationWhileLocked(directory,state,reason,options={}){{let active=state.prFeedbackPublication?.active,legacyRecord=active?void 0:state.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,state,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=(state.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:state.sessionID,intakeHeadSha:state.prHeadSha??"unknown",localHeadRef:"unknown",localHead:legacyRecord.localHead,remoteName:legacyRecord.remoteName,remoteUrlIdentity:void 0,remoteBranchRef:legacyRecord.remoteBranchRef,remoteRef:legacyRecord.remoteRef,revisionDigest:legacyRecord.revisionDigest,evidence:{stageAValidatedAt:state.prFeedbackStageA?.validatedAt??"unknown",batches:(state.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={...state,updatedAt:now,prFeedbackStageA:void 0,prFeedbackVerifications:void 0,prFeedbackGateBatches:void 0,prFeedbackScopes:void 0,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(state.prFeedbackPublication,invalidated,[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_publication_invalidated",sessionID:state.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),state=await readPrWorkflowGateState(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")return state;if(state.prFeedbackPublication||!state.prFeedbackReadyToPublish)return state;let legacy=state.prFeedbackReadyToPublish;return withSessionStateMutation(directory,normalizedSessionID,async()=>{let locked=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!locked||locked.mode!=="PR_FEEDBACK")return locked??state;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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state?.prFeedbackPublication,active=publication?.active;if(!state||!publication||!active||active.state!=="push_in_flight"||!publication.attempts.some((attempt)=>!attempt.result))return state;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={...state,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};return await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state.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(state){let active=state.prFeedbackPublication?.active,history=state.prFeedbackPublication?.history??[],attempts=state.prFeedbackPublication?.attempts??[];if(!active&&!state.prFeedbackReadyToPublish&&history.length===0)return null;let lines=[];if(state.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(`
1254
1255
  `)}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(`
1255
1256
  `)){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 tokens=command.trim().split(/\s+/);if(tokens.length!==4||tokens[0].toLowerCase()!=="git"||tokens[1].toLowerCase()!=="push"||tokens.some((token)=>/["'\\]/.test(token)))return{ok:!1,reason:"token-shape"};let[remoteToken,refspecToken]=[tokens[2],tokens[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:createHash49("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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),active=state?.prFeedbackPublication?.active;if(!state||state.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,state,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,state,`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:state.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={...state,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state.prFeedbackPublication,active,[],[...state.prFeedbackPublication?.attempts??[],attempt])};await writeStateWhileLocked(directory,nextState2),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state.sessionID,generation:active.generation,outcome:"completed",by:"no-op-observation",observedRemoteHead});return}let nextState={...state,updatedAt:now,prFeedbackPublication:nextPublicationContainer(state.prFeedbackPublication,{...active,state:"push_in_flight"},[],[...state.prFeedbackPublication?.attempts??[],baseAttempt])};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_started",sessionID:state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state?.prFeedbackPublication,active=publication?.active;if(!state||!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={...state,updatedAt:now,prFeedbackPublication:nextPublicationContainer(publication,{...active,state:"armed"},[],attempts)};await writeStateWhileLocked(directory,nextState),appendPublicationEvent(directory,{type:"pr_feedback_push_attempt_result",sessionID:state.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 state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID),publication=state?.prFeedbackPublication,active=publication?.active;if(!state||!publication||!active)return;if(active.state==="cancelled_without_publication"){nextRevision=state.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={...state,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 state=await ensurePublicationGenerationCurrent(directory,sessionID)??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");state=await reconcileForeignInFlightAttempt(directory,sessionID,options.currentCallId)??state??await requireBoundState2(directory,sessionID,"PR_FEEDBACK");let active=state.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,state,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 state}async function resolvePrReviewWriterRunId(directory,sessionID,requestedRunId){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW"),workflowInstanceId=workflowIdentity(state),normalizedRequested=requestedRunId?.trim()||void 0,stateBoundValues=[state.prReviewReservedRunId,state.prReviewTriggerEvalRunId,state.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(state.prReviewReservedRunId===resolvedRunId)return resolvedRunId;let nextState={...state,updatedAt:isoNow(),prReviewReservedRunId:resolvedRunId};return(await writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:state.workflowInstanceId})).prReviewReservedRunId??resolvedRunId}))}async function markPrReviewTriggerEvaluationComplete(directory,sessionID,runId,artifactPath){let state=(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(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation is already bound to run "${state.prReviewTriggerEvalRunId}"`);if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==normalizedRunId)throw Error(`BLOCKED: PR_REVIEW trigger evaluation run_id must match the findings artifact run "${state.prReviewArtifactRunId}"`);let nextState={...state,updatedAt:isoNow(),prReviewTriggerEvalPath:normalizedPath,prReviewTriggerEvalRunId:normalizedRunId};return await 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 state=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;if(state.prReviewTriggerLedger){let frozen;try{frozen=validatePrReviewInlineTriggerLedger(state.prReviewTriggerLedger)}catch(error49){throw Error(`BLOCKED: persisted PR_REVIEW trigger ledger is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}if(prReviewTriggerLedgerDigest(frozen.rows)!==prReviewTriggerLedgerDigest(ledger.rows))throw Error("BLOCKED: PR_REVIEW trigger_evaluation must remain exactly identical across every micro dispatch");return state}let nextState={...state,updatedAt:isoNow(),prReviewTriggerLedger:ledger.rows};return await persistState2(directory,nextState),nextState}async function assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds,options={}){let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),baseOnlyExplorerCheckpoint=boundary==="post_explorer"&&!state.prReviewTriggerEvalPath;if(!state.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)state=(await assertPrReviewBaseCoverageSettled2(directory,sessionID)).state;let persistedBoundaries=state.prReviewArtifactBoundaries??[],boundaryOrder=["post_explorer","post_reviewer","post_critic"],boundaryIndex=boundaryOrder.indexOf(boundary),requiredPriorBoundary=boundaryOrder[boundaryIndex-1];if(requiredPriorBoundary&&!persistedBoundaries.includes(requiredPriorBoundary))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings require the prior ${requiredPriorBoundary} checkpoint`);if(persistedBoundaries.some((persisted)=>boundaryOrder.indexOf(persisted)>boundaryIndex))throw Error(`BLOCKED: PR_REVIEW ${boundary} findings cannot be persisted after a later checkpoint`);let ctx=await createPrReviewGateContext2(directory,state);if(boundary==="post_reviewer")state=await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);else if(boundary==="post_critic"){if(await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx),derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"assertPrReviewArtifactBoundary(post_critic)").length>0)state=await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}if(state.prReviewArtifactRunId&&state.prReviewArtifactRunId!==runId)throw Error(`BLOCKED: PR_REVIEW artifacts are already bound to run "${state.prReviewArtifactRunId}"`);if(state.prReviewTriggerEvalRunId&&state.prReviewTriggerEvalRunId!==runId)throw Error(`BLOCKED: PR_REVIEW findings must use the same run as the trigger evaluation "${state.prReviewTriggerEvalRunId}"`);let expectedFindingIds=derivePrReviewCandidateInventory2(directory,state,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 state}async function assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(directory,sessionID,boundary,records){let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),violations=[],report=(findingId,field,expected,actual)=>{violations.push({findingId,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,state,await createPrReviewGateContext2(directory,state));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,state),reviewerVerdicts=authoritativeReviewerVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`),criticVerdicts=boundary==="post_critic"?authoritativeCriticVerdictsForGate(directory,state,ctx,`assertPrReviewArtifactRecordsMatchAuthoritativeVerdicts(${boundary})`):void 0;for(let record2 of records){let reviewer=reviewerVerdicts.get(record2.finding_id);if(!reviewer){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):
1256
1257
  ${lines.join(`
1257
1258
  `)}`)}}async function markPrReviewArtifactBoundary(directory,sessionID,runId,boundary,artifactPath,findingIds,handoffRequired){let state=await assertPrReviewArtifactBoundary(directory,sessionID,runId,boundary,findingIds),boundaries=new Set(state.prReviewArtifactBoundaries??[]);boundaries.add(boundary);let nextState={...state,updatedAt:isoNow(),prReviewArtifactRunId:runId,prReviewFindingsPath:artifactPath,prReviewArtifactBoundaries:[...boundaries],prReviewHandoffRequired:handoffRequired};return await persistState2(directory,nextState),nextState}async function markPrReviewHandoffComplete(directory,sessionID,runId,artifactPath){let normalizedSessionID=normalizeSessionID(sessionID);return withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await requireBoundState2(directory,normalizedSessionID,"PR_REVIEW");if(state.prReviewArtifactRunId!==runId||!(state.prReviewArtifactBoundaries??[]).includes("post_critic"))throw Error("BLOCKED: PR_REVIEW handoff requires the final findings boundary for the same run");let read=await readPrReviewFeedbackHandoffArtifact(directory,artifactPath),command=`/swarm pr-feedback ${read.artifact.pr_url} continue from .swarm/${artifactPath}`,consentInput={sessionID:normalizedSessionID,runId,handoffPath:artifactPath,handoffDigest:read.digest,prUrl:read.artifact.pr_url,prHeadSha:read.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(read.artifact.finding_ids),sourceWorkflowInstanceId:workflowIdentity(state)},existing=await readPrReviewFeedbackConsent(directory,runId),alreadyOffered=existing!==null;if(existing)assertMatchingPrReviewFeedbackConsent(existing,consentInput);else await writePrReviewFeedbackConsent(directory,{schema_version:1,state:"offered",session_id:normalizedSessionID,source_workflow_instance_id:workflowIdentity(state),run_id:runId,handoff_path:artifactPath,handoff_digest:read.digest,pr_url:read.artifact.pr_url,pr_head_sha:read.artifact.pr_head_sha.toLowerCase(),finding_ids_digest:consentInput.findingIdsDigest,confirmation_command:command,offered_at:isoNow()});if(alreadyOffered&&state.prReviewHandoffPath===artifactPath)return{state,alreadyOffered:!0};let nextState={...state,updatedAt:isoNow(),prReviewHandoffPath:artifactPath};return{state:await writeStateWhileLocked(directory,nextState),alreadyOffered}}))}function normalizePrReviewFeedbackHandoffPath(handoffPath){let normalized=handoffPath.trim().replace(/\\/g,"/"),relative26=normalized.startsWith(".swarm/")?normalized.slice(7):normalized,matched=relative26.match(PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN);if(!matched)return null;return{runId:matched[1],relativePath:relative26}}function buildAcceptedPrFeedbackContinuationCommands(confirmationCommand,relativeHandoffPath,requestedPrUrl){let commands=new Set([confirmationCommand]);if(!requestedPrUrl)commands.add(`/swarm pr-feedback continue from .swarm/${relativeHandoffPath}`);return commands}async function readBoundedSwarmRegularFile2(directory,relativePath,maxBytes,label){let absPath=validateSwarmPath(directory,relativePath),swarmRoot=path98.resolve(directory,".swarm"),rootStat,artifactStat;try{rootStat=await fsp7.lstat(swarmRoot,{bigint:!0}),artifactStat=await fsp7.lstat(absPath,{bigint:!0})}catch(error49){if(error49.code==="ENOENT")throw Error(`BLOCKED: ${label} "${relativePath}" does not exist`);throw error49}if(rootStat.isSymbolicLink()||!rootStat.isDirectory())throw Error(`BLOCKED: ${label} root must be a real project .swarm directory`);if(artifactStat.isSymbolicLink()||!artifactStat.isFile())throw Error(`BLOCKED: ${label} must be a bounded regular file`);if(artifactStat.size>BigInt(maxBytes))throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);let[realRoot,realArtifact]=await Promise.all([fsp7.realpath(swarmRoot),fsp7.realpath(absPath)]),relativeRealPath=path98.relative(realRoot,realArtifact);if(relativeRealPath===""||relativeRealPath===".."||relativeRealPath.startsWith(`..${path98.sep}`)||path98.isAbsolute(relativeRealPath))throw Error(`BLOCKED: ${label} escapes the project .swarm directory`);await _test_exports2.beforeBoundedSwarmFileOpen?.();let handle=await fsp7.open(realArtifact,"r");try{let openedStat=await handle.stat({bigint:!0});if(!openedStat.isFile()||openedStat.size>BigInt(maxBytes)||!sameBigIntFileIdentity(artifactStat,openedStat))throw Error(`BLOCKED: ${label} changed during its bounded read`);let[postRootStat,postArtifactStat,postRealRoot,postRealArtifact]=await Promise.all([fsp7.lstat(swarmRoot,{bigint:!0}),fsp7.lstat(absPath,{bigint:!0}),fsp7.realpath(swarmRoot),fsp7.realpath(absPath)]),postRelativeRealPath=path98.relative(postRealRoot,postRealArtifact);if(postRootStat.isSymbolicLink()||!postRootStat.isDirectory()||!sameBigIntFileIdentity(rootStat,postRootStat)||postArtifactStat.isSymbolicLink()||!postArtifactStat.isFile()||!sameBigIntFileIdentity(artifactStat,postArtifactStat)||!sameBigIntFileIdentity(openedStat,postArtifactStat)||normalizeComparableFsPath(realRoot)!==normalizeComparableFsPath(postRealRoot)||normalizeComparableFsPath(realArtifact)!==normalizeComparableFsPath(postRealArtifact)||postRelativeRealPath===""||postRelativeRealPath===".."||postRelativeRealPath.startsWith(`..${path98.sep}`)||path98.isAbsolute(postRelativeRealPath))throw Error(`BLOCKED: ${label} changed or escaped during its bounded read`);let buffer=Buffer.allocUnsafe(maxBytes+1),{bytesRead}=await handle.read(buffer,0,maxBytes+1,0);if(bytesRead>maxBytes)throw Error(`BLOCKED: ${label} exceeds ${maxBytes} bytes`);return buffer.subarray(0,bytesRead).toString("utf8")}finally{await handle.close()}}function prReviewRunReservationRelativePath(runId){return`pr-review/${runId}/run-reservation.json`}function prReviewFeedbackConsentRelativePath(runId){return`pr-review/${runId}/feedback-consent.json`}async function findOwnedPrReviewRunReservations(directory,sessionID,workflowInstanceId){let reviewRoot=validateSwarmPath(directory,"pr-review"),entries;try{entries=await fsp7.readdir(reviewRoot,{withFileTypes:!0})}catch(error49){if(error49.code==="ENOENT")return[];throw error49}if(entries.length>MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES)throw Error(`BLOCKED: PR_REVIEW reservation recovery expected at most ${MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES} run entries, got ${entries.length}`);let owned=[];for(let entry of entries){if(!entry.isDirectory()||!PrReviewRunIdSchema.safeParse(entry.name).success)continue;let reservation;try{reservation=await readPrReviewRunReservation(directory,entry.name)}catch{continue}if(reservation?.session_id===sessionID&&reservation.workflow_instance_id===workflowInstanceId&&reservation.run_id===entry.name)owned.push(entry.name)}return owned.sort()}function hashPrReviewFindingIds(ids){return createHash49("sha256").update([...new Set(ids)].sort().join("\x00"),"utf8").digest("hex")}async function readPrReviewRunReservation(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewRunReservationRelativePath(runId),PR_REVIEW_RUN_RESERVATION_MAX_BYTES,"PR_REVIEW run reservation"),parsed=PrReviewRunReservationSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW run reservation is invalid");return parsed.data}catch(error49){if((error49 instanceof Error?error49.message:String(error49)).includes("does not exist"))return null;throw error49}}async function tryCreatePrReviewRunReservation(directory,sessionID,workflowInstanceId,runId){let relativePath=prReviewRunReservationRelativePath(runId),absolutePath=validateSwarmPath(directory,relativePath),runDirectory=path98.dirname(absolutePath),payload=`${JSON.stringify({schema_version:1,session_id:sessionID,workflow_instance_id:workflowInstanceId,run_id:runId,reserved_at:isoNow()},null,2)}
1258
1259
  `;await fsp7.mkdir(runDirectory,{recursive:!0});try{return await fsp7.writeFile(absolutePath,payload,{encoding:"utf8",flag:"wx"}),"created"}catch(error49){if(error49.code!=="EEXIST")throw error49}let existing=await readPrReviewRunReservation(directory,runId);if(existing?.session_id===sessionID&&existing.workflow_instance_id===workflowInstanceId&&existing.run_id===runId)return"owned";let occupiedNames=new Set(["trigger-eval.json","findings.jsonl","feedback-handoff.json","feedback-consent.json"]);try{if((await fsp7.readdir(runDirectory)).some((entry)=>occupiedNames.has(entry)))return"occupied"}catch(error49){if(error49.code!=="ENOENT")throw error49}return"occupied"}async function readPrReviewFeedbackConsent(directory,runId){try{let raw=await readBoundedSwarmRegularFile2(directory,prReviewFeedbackConsentRelativePath(runId),PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES,"PR_REVIEW feedback consent artifact"),parsed=PrReviewFeedbackConsentSchema.safeParse(JSON.parse(raw));if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback consent artifact is invalid");return parsed.data}catch(error49){if((error49 instanceof Error?error49.message:String(error49)).includes("does not exist"))return null;throw error49}}async function writePrReviewFeedbackConsent(directory,record2){let relativePath=prReviewFeedbackConsentRelativePath(record2.run_id),absolutePath=validateSwarmPath(directory,relativePath);if(record2.state==="confirmed"){await writeAtomicJson2(directory,absolutePath,record2);return}let parent=path98.dirname(absolutePath),tempPath=path98.join(parent,`.feedback-consent.${randomUUID17()}.tmp`);await fsp7.mkdir(parent,{recursive:!0});try{await fsp7.writeFile(tempPath,`${JSON.stringify(record2,null,2)}
1259
- `,{encoding:"utf8",flag:"wx"}),await fsp7.link(tempPath,absolutePath)}finally{await fsp7.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash49("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function assertMatchingPrReviewFeedbackConsent(record2,input){if(record2.session_id!==input.sessionID||record2.run_id!==input.runId||record2.handoff_path!==input.handoffPath||record2.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record2.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record2.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record2.finding_ids_digest!==input.findingIdsDigest||record2.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash49("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,laneLiveness);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx)}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return{state,settlement}}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})}))}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state)!==declaration.revisionDigest)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[],callID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state.mode==="PR_FEEDBACK"&&state.prFeedbackReadyToPublish&&!state.prFeedbackPublication)state=await ensurePublicationGenerationCurrent(directory,sessionID)??state;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isTrustedWorkflowTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{}),isAllowlistedReadOnlyTool=normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool),readOnlyArgumentClassification=isAllowlistedReadOnlyTool?classifyReadOnlyToolArguments(normalizedTool,args2??{}):null,isNamedReadOnlyTool=isTrustedWorkflowTool||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0,isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0;if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(state.mode==="PR_REVIEW"&&isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!1)throw Error(`BLOCKED: PR_REVIEW is read-only; tool "${normalizedTool}" rejected argument "${readOnlyArgumentClassification.path}": ${readOnlyArgumentClassification.constraint}`);if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool3&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool3&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, run `git rev-parse --verify <full_pr_head_sha>^0`, run `git cat-file -t <full_pr_head_sha>` (which must print `commit`), then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool3&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function readPrReviewReentryBindingContext(directory,sessionID){let state=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state?prReviewReentryBindingFromState(directory,state):null}async function prReviewReentryBindingFromState(directory,state){if(state.mode!=="PR_REVIEW"||!state.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state);return{prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state.revision,...state.workflowInstanceId?{workflowInstanceId:state.workflowInstanceId}:{},...state.prReviewArtifactRunId??state.prReviewReservedRunId?{runId:state.prReviewArtifactRunId??state.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)return!1;let binding=await prReviewReentryBindingFromState(directory,state);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)return null;let binding=await prReviewReentryBindingFromState(directory,state);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,options?.laneLiveness);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,ctx.revisionDigest);if(settlement.kind==="NO_COVERAGE"){if(settlement.liveDimensions.length>0)throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${settlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);if(verdict!=="INCOMPLETE")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);let noCoverageRunId=state.prReviewArtifactRunId??state.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let preAllowed=allowedPrReviewReportVerdicts(settlement.kind);if(!preAllowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${settlement.kind} completion allows report_verdict ${preAllowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`);let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");let allowed=allowedPrReviewReportVerdicts(ready.settlement.kind);if(!allowed.includes(verdict))throw Error(`BLOCKED: PR_REVIEW ${ready.settlement.kind} completion allows report_verdict ${allowed.join(" | ")}; got "${verdict}". Partial coverage never approves and never claims a full review.`)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}let localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");let commitCount=await _test_exports2.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead);if(commitCount===0){if(localHead!==state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires HEAD to equal the immutable intake head (history diverged; resolve it or rebind via rebind_pr_feedback_head)");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readLegacySettledFeedbackClassifications(directory,readyState),inventory=readyState.prFeedbackInventory??[],offenders=inventory.filter((itemId)=>!classifications.has(itemId)||!FEEDBACK_NO_CHANGE_CLASSIFICATIONS.has(classifications.get(itemId)));if(offenders.length>0)throw Error(`BLOCKED: PR_FEEDBACK zero-commit completion requires every inventory item verified as a no-change outcome (DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION); offending items: ${offenders.slice(0,10).join(", ")}. Items with confirmed content changes must follow the exactly-one-reviewed-commit path.`);try{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports2.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state.revision),"completed"}function noActiveGateError(sessionID){return Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`)}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw noActiveGateError(sessionID);return state}async function requireBoundState2(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);assertNoDuplicates(reviewItemIds,"review item ids within one lane")}let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function unsafeReadOnlyArgument(path99,constraint,value){return{safe:!1,path:path99||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function classifyReadOnlyToolArguments(toolName,value,key2="",path99="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path99,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return unsafeReadOnlyArgument(path99,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,"HTTP method/verb must be GET or HEAD for a read-only tool",value);if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return unsafeReadOnlyArgument(path99,"query/request text contains a mutating operation",value);return/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)?unsafeReadOnlyArgument(path99,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key2,`${path99}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path99,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path99,"argument type is not supported by the read-only classifier",value)}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(hasUnsafeShellControlSyntax(command))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted2=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only."}}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}function assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory2(directory,state,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful2=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state.prReviewTriggerEvalPath)for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful2.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}let degradedSourceKeys=new Set;if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{let triggerStat=statSync36(triggerPath);if(!triggerStat.isFile()||triggerStat.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error("trigger evaluation artifact exceeds its read bound");triggerArtifact=JSON.parse(readFileSync37(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id});for(let degradation of receipt.coverageDegradations)degradedSourceKeys.add(`${degradation.source_batch_id}\x00${degradation.source_lane_id}`)}let candidateIds=[],candidateSeverities=new Map,extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha)continue;let structured=record2.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey)){extractedLaneKeys.add(laneKey);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact){if(degradedSourceKeys.has(`${source.batchId}\x00${source.laneId}`))continue;throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),ctx.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifactCached(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds2(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims2(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.has(lane.workflowLane))}function authoritativeReviewerClaims2(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[reviewerItemBindingKey(itemId)]=rowDigest}return bindings}function derivePrReviewCriticInventory2(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims2(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory2(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope:state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful2.add(obligation)}return successful2}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity2(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic";return analyzeLegacyVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion2({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state.workflowInstanceId,workflowRevision:record2.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,cleanAttestationSalvaged=!1,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:acceptPartial,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||Boolean(parsed.clean_attestation_salvaged)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion2(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return recordIntegrity;let structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt","missing structured receipt (legacy transcript adapter disabled)");let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode,input.result.transcriptIncomplete===!0)})),salvagedLanes=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims2(input.directory,state,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzeLegacyVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!legacyFeedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}async function persistState2(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp7.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(parsed.success)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let invalidError=Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(typeof parsedJson!=="object"||parsedJson===null||Array.isArray(parsedJson))throw invalidError;let rawRecord=parsedJson,salvagedSessionID=exports_external.string().min(1).safeParse(rawRecord.sessionID),salvagedMode=exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).safeParse(rawRecord.mode);if(!salvagedSessionID.success||!salvagedMode.success)throw invalidError;let salvagedRevision=exports_external.number().int().nonnegative().safeParse(rawRecord.revision),salvagedHead=exports_external.string().min(1).safeParse(rawRecord.prHeadSha),salvagedActivatedAt=exports_external.string().min(1).safeParse(rawRecord.activatedAt),salvagedUpdatedAt=exports_external.string().min(1).safeParse(rawRecord.updatedAt),armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,schemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue2)=>boundSalvagedSchemaError(`${issue2.path.join(".")||"(root)"}: ${issue2.message}`)),disclosure=`DEGRADED: PR workflow gate state for session "${normalizedSessionID}" failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). Schema errors: ${schemaErrors.join("; ")}.`+(salvagedRevision.success?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":"");return{state:{schemaVersion:GATE_SCHEMA_VERSION,revision:salvagedRevision.success?salvagedRevision.data:0,sessionID:salvagedSessionID.data,mode:salvagedMode.data,activatedAt:salvagedActivatedAt.success?salvagedActivatedAt.data:isoNow(),updatedAt:salvagedUpdatedAt.success?salvagedUpdatedAt.data:isoNow(),...salvagedHead.success?{prHeadSha:salvagedHead.data}:{},...salvagedArmed.success?{prFeedbackReadyToPublish:salvagedArmed.data}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}var PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,GATE_SCHEMA_VERSION=1,MAX_WORKFLOW_BATCHES=128,MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS=128,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,MAX_DISCLOSED_LANE_IDS=10,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,CAS_ESCAPE_DISCLOSURE="state revision unsalvageable; cleared without compare-and-swap",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS=180000,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,_test_exports2,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,MAX_SALVAGED_SCHEMA_ERRORS=10,MAX_SALVAGED_SCHEMA_ERROR_CHARS=240;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_collection_receipt();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_legacy_transcript_adapter();init_persistence();init_reducer();init_scope_binding();init_state2();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,MAX_PR_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.optional()}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).strict(),PrFeedbackInventoryAmendmentRecordSchema=exports_external.object({entry:exports_external.string().min(1),amendedAt:exports_external.string().min(1),batch:exports_external.number().int().positive()}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").optional()}).passthrough(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewResilience:PrReviewResilienceStateRecordSchema.optional(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewTriggerEvalRunId:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).optional(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackInventoryAmendments:exports_external.array(PrFeedbackInventoryAmendmentRecordSchema).max(MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_WORKFLOW_STALE_LANE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES=new Set(["pending","running"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),_test_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforePrReviewReentryReservation=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return derivePrReviewCandidateInventory2(directory,state,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp7.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
1260
+ `,{encoding:"utf8",flag:"wx"}),await fsp7.link(tempPath,absolutePath)}finally{await fsp7.rm(tempPath,{force:!0}).catch(()=>{return})}}async function readPrReviewFeedbackHandoffArtifact(directory,relativePath){let raw=await readBoundedSwarmRegularFile2(directory,relativePath,PR_REVIEW_HANDOFF_MAX_BYTES,"PR_REVIEW feedback handoff artifact"),parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is not valid JSON")}let parsed=PrReviewFeedbackHandoffArtifactSchema.safeParse(parsedJson);if(!parsed.success)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact is invalid");if(new Set(parsed.data.finding_ids).size!==parsed.data.finding_ids.length)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact contains duplicate finding IDs");return{artifact:parsed.data,digest:createHash49("sha256").update(raw,"utf8").digest("hex")}}async function readActionableReviewFindingIds(directory,state,runId){let expectedPath=`pr-review/${runId}/findings.jsonl`;if(state.prReviewFindingsPath!==expectedPath)throw Error(`BLOCKED: PR_REVIEW transition requires the exact final findings artifact "${expectedPath}"`);let raw=await readBoundedSwarmRegularFile2(directory,expectedPath,PR_REVIEW_FINDINGS_MAX_BYTES,"PR_REVIEW final findings artifact"),latest=new Map;for(let[index,line]of raw.split(/\r?\n/).entries()){if(!line.trim())continue;let value;try{value=JSON.parse(line)}catch{throw Error(`BLOCKED: PR_REVIEW final findings artifact contains invalid JSON at line ${index+1}`)}let parsed=PrReviewFindingProjectionSchema.safeParse(value);if(!parsed.success)throw Error(`BLOCKED: PR_REVIEW final findings artifact contains an invalid record at line ${index+1}`);latest.set(parsed.data.finding_id,parsed.data)}return[...latest.values()].filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id).sort()}function canonicalGitHubPrUrl(value){try{let url2=new URL(value);if(url2.protocol!=="https:"||url2.hostname.toLowerCase()!=="github.com")return null;let matched=url2.pathname.match(/^\/([^/]+)\/([^/]+)\/pull\/(\d+)\/?$/);if(!matched)return null;let prNumber=Number(matched[3]);if(!Number.isSafeInteger(prNumber)||prNumber<=0)return null;return`github.com/${matched[1].toLowerCase()}/${matched[2].toLowerCase()}/pull/${prNumber}`}catch{return null}}function assertMatchingPrReviewFeedbackConsent(record2,input){if(record2.session_id!==input.sessionID||record2.run_id!==input.runId||record2.handoff_path!==input.handoffPath||record2.handoff_digest!==input.handoffDigest||canonicalGitHubPrUrl(record2.pr_url)!==canonicalGitHubPrUrl(input.prUrl)||record2.pr_head_sha.toLowerCase()!==input.prHeadSha.toLowerCase()||record2.finding_ids_digest!==input.findingIdsDigest||record2.source_workflow_instance_id!==input.sourceWorkflowInstanceId)throw Error("BLOCKED: PR_REVIEW feedback consent artifact does not match the requested handoff; remove the stale sidecar or repeat the exact continuation offer")}function workflowIdentity(state){return state.workflowInstanceId??`legacy-${createHash49("sha256").update(`${state.sessionID}\x00${state.mode}\x00${state.activatedAt}`).digest("hex").slice(0,32)}`}function sameHandoffIds(left,right){let normalizedLeft=[...new Set(left)].sort(),normalizedRight=[...new Set(right)].sort();return sameStringArray(normalizedLeft,normalizedRight)}function assertSamePrFeedbackHandoff(state,relativePath,read,requestedPrUrl){let existing=state.prFeedbackReviewHandoff;if(!existing)throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK without persisted review handoff provenance`);let artifactPr=canonicalGitHubPrUrl(read.artifact.pr_url),requestedPr=requestedPrUrl?canonicalGitHubPrUrl(requestedPrUrl):artifactPr;if(!artifactPr||requestedPrUrl&&requestedPr!==artifactPr||existing.path!==relativePath||existing.runId!==read.artifact.run_id||existing.digest!==read.digest||existing.sourcePrHeadSha.toLowerCase()!==read.artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(existing.prUrl)!==artifactPr||!sameHandoffIds(existing.findingIds,read.artifact.finding_ids))throw Error(`BLOCKED: session "${state.sessionID}" is already active in PR_FEEDBACK for a different handoff or PR`)}async function assertPrReviewTerminalReady(directory,sessionID,laneLiveness){let state=await requireBoundState2(directory,sessionID,"PR_REVIEW");await assertPrReviewCleanCheckout(directory,"PR_REVIEW");let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,laneLiveness);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: PR_REVIEW transition has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let ctx=await createPrReviewGateContext2(directory,state),{settlement}=await assertPrReviewBaseCoverageSettled2(directory,sessionID,ctx);if(!state.prReviewTriggerEvalPath)throw Error("BLOCKED: PR_REVIEW transition requires a persisted trigger evaluation artifact");if((state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="council"))await assertPrReviewValidationSettled(directory,sessionID,"council",ctx);await assertPrReviewValidationSettled(directory,sessionID,"reviewer",ctx);let criticInventory=derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,"completePrWorkflow critic-coverage gate");if(criticInventory.length>0){if(!(state.prReviewValidationBatches??[]).some((batch)=>batch.phase==="critic"))throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${criticInventory.join(", ")}`);await assertPrReviewValidationSettled(directory,sessionID,"critic",ctx);let criticVerdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx),reviewerClaims=authoritativeReviewerClaims2(directory,state,ctx),settledReceipts=[];for(let[itemId,verdict]of criticVerdicts){if(verdict.status!=="UPHELD"&&verdict.status!=="DOWNGRADED"&&verdict.status!=="DISPROVED")continue;let reviewerRowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!reviewerRowDigest)continue;settledReceipts.push({findingId:itemId,status:verdict.status,reviewerRowDigest})}if(reducePrReviewEvent(state,{type:"critic_result_recorded",criticRequiredFindingIds:criticInventory,criticSettledReceipts:settledReceipts}).status==="rejected"){let settledIds=new Set(settledReceipts.map((r)=>r.findingId)),unfulfilled=criticInventory.filter((id)=>!settledIds.has(id));throw Error(`BLOCKED: PR_REVIEW reviewer verdicts require critic coverage for: ${unfulfilled.join(", ")}`)}}let requiredBoundaries=["post_explorer","post_reviewer","post_critic"],persistedBoundaries=new Set(state.prReviewArtifactBoundaries??[]),missing=requiredBoundaries.filter((boundary)=>!persistedBoundaries.has(boundary));if(!state.prReviewFindingsPath||missing.length>0)throw Error(`BLOCKED: PR_REVIEW transition requires durable findings checkpoints; missing: ${missing.join(", ")||"findings path"}`);if(state.prReviewHandoffRequired&&!state.prReviewHandoffPath)throw Error("BLOCKED: PR_REVIEW actionable findings require a persisted feedback handoff artifact");return{state,settlement}}async function transitionPrReviewToFeedback(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID),normalizedHandoff=normalizePrReviewFeedbackHandoffPath(request.handoffPath);if(!normalizedHandoff||normalizedHandoff.runId!==request.runId)throw Error("BLOCKED: PR-feedback continuation must use .swarm/pr-review/<run_id>/feedback-handoff.json");let preliminaryRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath),artifact=preliminaryRead.artifact,artifactPr=canonicalGitHubPrUrl(artifact.pr_url),requestedPr=request.prUrl?canonicalGitHubPrUrl(request.prUrl):null;if(!artifactPr||request.prUrl&&requestedPr!==artifactPr)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested GitHub PR URL");if(artifact.run_id!==request.runId)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact does not match the requested review run");let preliminary=await readPrWorkflowGateState(directory,normalizedSessionID);if(preliminary?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(preliminary,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),preliminary;let sourceIdentity,expectedConsentSourceIdentity,sourceRevision=0,provenance;if(preliminary){if(preliminary.mode!=="PR_REVIEW")throw wrongModeError(preliminary,"PR_REVIEW");let ready=(await assertPrReviewTerminalReady(directory,normalizedSessionID,request.laneLiveness)).state;if(workflowIdentity(ready)!==workflowIdentity(preliminary)||ready.revision!==preliminary.revision||ready.mode!=="PR_REVIEW"||ready.prReviewHandoffPath!==normalizedHandoff.relativePath||ready.prReviewArtifactRunId!==request.runId||!ready.prHeadSha||ready.prHeadSha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||canonicalGitHubPrUrl(artifact.pr_url)!==canonicalGitHubPrUrl(request.prUrl??artifact.pr_url))throw Error("BLOCKED: PR_REVIEW feedback handoff does not match the terminal active review state");let actionableIds=await readActionableReviewFindingIds(directory,ready,request.runId);if(!sameHandoffIds(actionableIds,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff finding IDs do not match the authoritative final findings ledger");sourceIdentity=workflowIdentity(ready),expectedConsentSourceIdentity=sourceIdentity,sourceRevision=ready.revision,provenance="active-review-v1"}else{let reservation=await readPrReviewRunReservation(directory,request.runId);if(!reservation||reservation.session_id!==normalizedSessionID||reservation.run_id!==request.runId)throw Error("BLOCKED: completed PR_REVIEW continuation requires the matching durable run reservation for this session");expectedConsentSourceIdentity=reservation.workflow_instance_id,sourceIdentity=expectedConsentSourceIdentity,provenance="external-v1"}let consent=await readPrReviewFeedbackConsent(directory,request.runId);if(!consent)throw Error("BLOCKED: PR_FEEDBACK continuation requires explicit confirmation; repeat the exact continuation command first");assertMatchingPrReviewFeedbackConsent(consent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:preliminaryRead.digest,prUrl:artifact.pr_url,prHeadSha:artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity});let exactCommand=request.exactCommand?.trim(),acceptedContinuationCommands=buildAcceptedPrFeedbackContinuationCommands(consent.confirmation_command,normalizedHandoff.relativePath,request.prUrl);if(request.confirmedByUser!==!0||!exactCommand||!acceptedContinuationCommands.has(exactCommand))throw Error(`BLOCKED: PR_FEEDBACK continuation requires explicit confirmation with the offered command: ${consent.confirmation_command}`);return await _test_exports2.beforePrFeedbackTransitionLock?.(),withPrWorkflowCheckoutMutationLock(directory,()=>withSessionStateMutation(directory,normalizedSessionID,async()=>{let current=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(current?.mode==="PR_FEEDBACK")return assertSamePrFeedbackHandoff(current,normalizedHandoff.relativePath,preliminaryRead,request.prUrl),current;if(provenance==="active-review-v1"){if(!current||current.mode!=="PR_REVIEW"||workflowIdentity(current)!==sourceIdentity||current.revision!==sourceRevision||current.prHeadSha?.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||current.prReviewArtifactRunId!==request.runId||current.prReviewHandoffPath!==normalizedHandoff.relativePath)throw Error("BLOCKED: PR_REVIEW state changed while validating the feedback handoff; retry from current state")}else if(current)throw Error("BLOCKED: another PR workflow became active while validating the external handoff");if(provenance==="external-v1"){let lockedReservation=await readPrReviewRunReservation(directory,request.runId);if(!lockedReservation||lockedReservation.session_id!==normalizedSessionID||lockedReservation.workflow_instance_id!==expectedConsentSourceIdentity)throw Error("BLOCKED: PR_REVIEW run reservation changed during external feedback transition")}let lockedRead=await readPrReviewFeedbackHandoffArtifact(directory,normalizedHandoff.relativePath);if(lockedRead.digest!==preliminaryRead.digest)throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");if(artifactPr!==canonicalGitHubPrUrl(lockedRead.artifact.pr_url)||lockedRead.artifact.run_id!==request.runId||lockedRead.artifact.pr_head_sha.toLowerCase()!==artifact.pr_head_sha.toLowerCase()||!sameHandoffIds(lockedRead.artifact.finding_ids,artifact.finding_ids))throw Error("BLOCKED: PR_REVIEW feedback handoff artifact changed during transition");let lockedConsent=await readPrReviewFeedbackConsent(directory,request.runId);if(!lockedConsent)throw Error("BLOCKED: PR_REVIEW feedback consent artifact disappeared during transition");if(assertMatchingPrReviewFeedbackConsent(lockedConsent,{sessionID:normalizedSessionID,runId:request.runId,handoffPath:normalizedHandoff.relativePath,handoffDigest:lockedRead.digest,prUrl:lockedRead.artifact.pr_url,prHeadSha:lockedRead.artifact.pr_head_sha,findingIdsDigest:hashPrReviewFindingIds(lockedRead.artifact.finding_ids),sourceWorkflowInstanceId:expectedConsentSourceIdentity}),!buildAcceptedPrFeedbackContinuationCommands(lockedConsent.confirmation_command,normalizedHandoff.relativePath,request.prUrl).has(exactCommand))throw Error("BLOCKED: PR_FEEDBACK continuation command changed during transition");if(lockedConsent.state==="offered")await writePrReviewFeedbackConsent(directory,{...lockedConsent,state:"confirmed",confirmed_at:isoNow()});let timestamp=isoNow(),nextState={schemaVersion:GATE_SCHEMA_VERSION,revision:sourceRevision,workflowInstanceId:randomUUID17(),sessionID:normalizedSessionID,mode:"PR_FEEDBACK",activatedAt:timestamp,updatedAt:timestamp,prFeedbackReviewHandoff:{path:normalizedHandoff.relativePath,runId:lockedRead.artifact.run_id,sourcePrHeadSha:lockedRead.artifact.pr_head_sha.toLowerCase(),prUrl:lockedRead.artifact.pr_url,findingIds:[...new Set(lockedRead.artifact.finding_ids)].sort(),digest:preliminaryRead.digest,sourceWorkflowInstanceId:sourceIdentity,provenance},prFeedbackTargetUrl:artifact.pr_url};return writeStateWhileLocked(directory,nextState,{replaceWorkflowInstanceId:provenance==="active-review-v1"?current?.workflowInstanceId:void 0})}))}async function declarePrFeedbackScope(directory,sessionID,taskId,files){let state=await assertPrFeedbackVerificationSettled(directory,sessionID),revisionDigest=await currentPrFeedbackRevisionDigest(directory,state),previous=state.prFeedbackScopes??[];if(previous.find((entry)=>entry.taskId===taskId)?.consumedByCallId)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed; use a fresh task_id for any retry`);let record2={taskId,files,revisionDigest,declaredAt:isoNow()},nextState={...state,updatedAt:isoNow(),prFeedbackScopes:[...previous.filter((entry)=>entry.taskId!==taskId),record2]};return await persistState2(directory,nextState),nextState}async function resolvePrFeedbackScopeDeclaration(directory,sessionID,taskId){let state=await readPrWorkflowGateState(directory,sessionID);if(state?.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;return await assertPrFeedbackVerificationSettled(directory,sessionID),await currentPrFeedbackRevisionDigest(directory,state)===declaration.revisionDigest?declaration:null}async function consumePrFeedbackScopeDeclaration(directory,sessionID,taskId,callID,expected){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state||state.mode!=="PR_FEEDBACK")return null;let declaration=(state.prFeedbackScopes??[]).find((entry)=>entry.taskId===taskId);if(!declaration)return null;if(declaration.declaredAt!==expected.declaredAt||declaration.revisionDigest!==expected.revisionDigest||JSON.stringify(declaration.files)!==JSON.stringify(expected.files))return null;if(await assertPrFeedbackVerificationSettledState(directory,state)!==declaration.revisionDigest)return null;if(declaration.consumedByCallId&&declaration.consumedByCallId!==callID)throw Error(`SCOPE_NOT_DECLARED: PR-feedback scope ${taskId} was already consumed by another Task call`);if(declaration.consumedByCallId===callID)return declaration;let consumed={...declaration,consumedByCallId:callID};return await writeStateWhileLocked(directory,{...state,updatedAt:isoNow(),prFeedbackScopes:(state.prFeedbackScopes??[]).map((entry)=>entry.taskId===taskId?consumed:entry)}),consumed})}async function validatePrFeedbackScopeBinding(directory,binding){if(!binding.workflowSessionId||!binding.workflowRevisionDigest)return!1;let declaration=await resolvePrFeedbackScopeDeclaration(directory,binding.workflowSessionId,binding.taskId);return Boolean(declaration&&declaration.consumedByCallId===binding.dispatchCallId&&declaration.revisionDigest===binding.workflowRevisionDigest&&JSON.stringify(declaration.files)===JSON.stringify(binding.files))}async function enforcePrWorkflowToolBefore(directory,sessionID,toolName,args2,generatedAgentNames=[],callID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state){let normalizedEarlyTool=toolName.toLowerCase();if(normalizedEarlyTool==="bash"||normalizedEarlyTool==="shell"){let earlyCommand=typeof args2?.command==="string"?args2.command.trim():"";if(/\bgit\b/.test(earlyCommand)&&(/\bpush\b/.test(earlyCommand)||/\bsend-pack\b/.test(earlyCommand))||/\bgh\s+api\b/i.test(earlyCommand)&&/refs\/heads\//.test(earlyCommand)){let dangling=findDanglingLivePublicationGeneration(directory,sessionID);if(dangling)throw Error(`BLOCKED: PR_FEEDBACK publication generation ${dangling.generation} for this session is live in the audit trail but its gate state is missing (deleted or moved by hand). Publication commands fail closed until the window is resolved: use abort_pr_workflow with kind "cancel-publication", cancel_publication: true, and a reason to record the audited no-publish terminal, or restore the gate state from backup.`)}}return}if(state.mode==="PR_FEEDBACK"&&state.prFeedbackReadyToPublish&&!state.prFeedbackPublication)state=await ensurePublicationGenerationCurrent(directory,sessionID)??state;let normalizedTool=toolName.toLowerCase(),isDirectAgentTask=normalizedTool==="task"||normalizedTool==="run_agent",requestedAgentFields=["subagent_type","agent"].filter((field)=>Object.hasOwn(args2??{},field)),requestedRoles=requestedAgentFields.map((field)=>{let value=args2?.[field];if(typeof value!=="string"||!value.trim())return"";return resolveGeneratedAgentRole(value.trim(),generatedAgentNames)}),isDirectWrite=WRITE_TOOL_NAMES.includes(normalizedTool),command=typeof args2?.command==="string"?args2.command.trim():"",serializedArgs=JSON.stringify(args2??{}),referencesProtectedWorkflowEvidence=containsProtectedWorkflowPath(command||serializedArgs),isInternalWorkflowTool=isPrWorkflowControllerTool(state.mode,normalizedTool),isShellTool3=normalizedTool==="bash"||normalizedTool==="shell",isReadOnlyShell=!1,shellPermissionEnvelope=null;if(isShellTool3&&command.length>0){let trackingFetchTarget=state.prHeadSha?await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory):null;shellPermissionEnvelope={allowCheckout:!state.prHeadSha,allowFetch:!state.prHeadSha,allowTrackingFetch:Boolean(state.prHeadSha),trackingFetchTarget},isReadOnlyShell=isAllowedPrWorkflowReadOnlyShell(command,shellPermissionEnvelope)}let trustedCapability=getPrWorkflowToolCapability(normalizedTool,state.mode),isTrustedWorkflowTool=trustedCapability!==null&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{}),isAllowlistedReadOnlyTool=normalizedTool!=="build_check"&&isAllowedPrReviewReadOnlyToolName(normalizedTool),readOnlyArgumentClassification=isAllowlistedReadOnlyTool?classifyReadOnlyToolArguments(normalizedTool,args2??{}):null,isNamedReadOnlyTool=isTrustedWorkflowTool||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0,isRecoverySafeEvidenceTool=trustedCapability==="observe"&&isTrustedPrWorkflowToolInvocationSafe(normalizedTool,args2??{})||isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!0;if(state.checkoutRecovery){if(isRecoverySafeEvidenceTool||isReadOnlyShell||normalizedTool==="abort_pr_workflow"||normalizedTool==="pr_workflow_status"||normalizedTool==="prepare_pr_workflow_checkout")return;throw Error(`BLOCKED: ${state.mode} requires manual Git recovery before controller work can continue. code=${state.checkoutRecovery.code} retryable=false required_action=${state.checkoutRecovery.requiredAction}`)}if(state.mode==="PR_REVIEW"&&isAllowlistedReadOnlyTool&&readOnlyArgumentClassification?.safe===!1)throw Error(`BLOCKED: PR_REVIEW is read-only; tool "${normalizedTool}" rejected argument "${readOnlyArgumentClassification.path}": ${readOnlyArgumentClassification.constraint}`);if(referencesProtectedWorkflowEvidence&&!isInternalWorkflowTool&&!isNamedReadOnlyTool&&!isReadOnlyShell)throw Error(`BLOCKED: active ${state.mode} workflow evidence under .swarm is controller-owned and cannot be modified directly`);let isShellCommandRequiringVerification=isShellTool3&&command.length>0&&!isReadOnlyShell,isRemoteReviewTool=/(?:git|github|pull|(?:^|[_-])pr(?:[_-]|$)|issue|review)/i.test(normalizedTool),hasRemoteMutationVerb=/(?:^|[_-])(?:add|approve|cancel|close|comment|commit|convert|create|delete|dismiss|edit|mark|merge|push|ready|reopen|rerun|resolve|submit|transfer|unresolve|update)(?:[_-]|$)/i.test(normalizedTool),hasRemoteReadVerb=/(?:^|[_-])(?:github|git)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool)||/(?:^|[_-])(?:github|git)[_-]+(?:pull[_-]+request|pr|issue|review[_-]+thread)[_-]+(?:check|checks|checkout|diff|fetch|get|inspect|list|read|search|status|view)(?:[_-]|$)/i.test(normalizedTool),isRemoteMutationTool=isRemoteReviewTool&&(hasRemoteMutationVerb||!hasRemoteReadVerb),isRemoteCheckoutTool=/(?:^|[_-])(?:github|git)[_-]+checkout(?:[_-]|$)/i.test(normalizedTool),isShellCheckout=(normalizedTool==="bash"||normalizedTool==="shell")&&(/\bgit\b(?:(?![;&|]).){0,200}\b(?:checkout|switch)\b/i.test(command)||/\bgh\s+pr\s+checkout\b/i.test(command)),stderrMergeNormalizedCommand=command.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"").trim(),isCanonicalReviewCheckout=/^git\s+switch\s+--detach\s+[0-9a-f]{40,64}$/i.test(stderrMergeNormalizedCommand),detachedFeedbackSwitchMatch=command.match(/^git\s+switch\s+--detach\s+(\S+)$/i),isDetachedFeedbackCheckout=Boolean(detachedFeedbackSwitchMatch?.[1]&&isSafeGitRefToken(detachedFeedbackSwitchMatch[1]))||/^gh\s+pr\s+checkout\b.*\s--detach(?:\s|$)/i.test(command),containsGitCommitShell=isShellCommandRequiringVerification&&/\bgit\b(?:(?![;&|]).){0,200}\bcommit\b/i.test(command),isStandaloneGitCommitShell=containsGitCommitShell&&isSafeStandaloneGitCommit(command),isPublicationShell=isShellCommandRequiringVerification&&(/\bgit\b(?:(?![;&|]).){0,200}\bpush\b/i.test(command)||/\bgh\s+(?:api|pr|issue|run)\b/i.test(command)),isPublicationTool=!isInternalWorkflowTool&&isRemoteMutationTool,isCoderTask=isDirectAgentTask&&requestedRoles.length>0&&requestedRoles.every((role)=>role==="coder"),blockedShellDiagnosis=isShellTool3&&command&&!isReadOnlyShell&&shellPermissionEnvelope?` ${describeBlockedPrReviewShellCommand(command,shellPermissionEnvelope)}`:"";if(state.mode==="PR_REVIEW"){let hasAuthorizedDirectReentry=!1;if(isDirectAgentTask&&requestedAgentFields.length===1&&requestedAgentFields[0]==="subagent_type"&&requestedRoles.length===1&&(requestedRoles[0]==="reviewer"||requestedRoles[0]==="test_engineer")&&callID)hasAuthorizedDirectReentry=await hasActivePrReviewReentryAuthorization(directory,sessionID,{role:requestedRoles[0]});if(!(isInternalWorkflowTool||hasAuthorizedDirectReentry||isNamedReadOnlyTool||isReadOnlyShell&&(!isShellCheckout||isCanonicalReviewCheckout))||Boolean(state.prHeadSha)&&(isRemoteCheckoutTool||isShellCheckout)){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_REVIEW checkout must use standalone commands: fetch the PR head, run `git rev-parse --verify <full_pr_head_sha>^0`, run `git cat-file -t <full_pr_head_sha>` (which must print `commit`), then run `git switch --detach <full_pr_head_sha>` and bind that exact head before dispatching explorer lanes. Do not use `--track FETCH_HEAD`."+blockedShellDiagnosis);throw Error("BLOCKED: PR_REVIEW is read-only and fail-closed; only controller tools and positively classified observation tools are allowed, and every agent lane requires structured dispatch_lanes_async"+describePrWorkflowControllerToolNames(state.mode)+blockedShellDiagnosis)}return}if(isDirectAgentTask&&!isCoderTask)throw Error("BLOCKED: PR_FEEDBACK reviewer, test, critic, explorer, and unknown agent lanes require structured dispatch_lanes_async provenance");if(!isInternalWorkflowTool&&!isDirectAgentTask&&!isDirectWrite&&!isShellTool3&&!isNamedReadOnlyTool)throw Error("BLOCKED: PR_FEEDBACK rejects unclassified plugin/MCP tools; use positively classified observation tools, built-in structured write tools after verification, or the workflow controller"+describePrWorkflowControllerToolNames(state.mode));if(state.prHeadSha&&(isShellCheckout||isRemoteCheckoutTool))throw Error("BLOCKED: PR_FEEDBACK checkout is immutable after exact PR head binding");if(containsGitCommitShell&&state.prFeedbackReadyToPublish)throw Error("BLOCKED: PR_FEEDBACK is armed for publication; the approved commit is immutable");if((containsGitCommitShell||isPublicationShell)&&hasUnsafeShellControlSyntax(command))throw Error("BLOCKED: PR_FEEDBACK publication commands must be standalone shell commands without control, redirection, or command-substitution syntax");if(containsGitCommitShell&&!isStandaloneGitCommitShell)throw Error("BLOCKED: PR_FEEDBACK commit must use a standalone git commit command after every ordered local gate passes");if(state.prFeedbackReadyToPublish){if(normalizedTool==="complete_pr_workflow")return;if(normalizedTool==="invalidate_pr_feedback_publication")return;if(normalizedTool==="abort_pr_workflow"&&args2?.cancel_publication===!0)return;if(isNamedReadOnlyTool)return;if((normalizedTool==="bash"||normalizedTool==="shell")&&command.length>0&&isAllowedPrWorkflowReadOnlyShell(command,{allowCheckout:!1,allowFetch:!1,allowTrackingFetch:!1}))return;if(normalizedTool==="bash"||normalizedTool==="shell"){let armed=(await assertPrFeedbackPublicationArmed(directory,sessionID,{currentCallId:callID})).prFeedbackReadyToPublish,intent=parseExactBoundPushIntent(command,armed);if(intent.ok&&intent.intent&&intent.digest){await admitPrFeedbackPushAttempt(directory,sessionID,callID,intent.intent,intent.digest);return}throw Error(`BLOCKED: PR_FEEDBACK is armed for publication; only the exact approved push is allowed: ${expectedBoundPushCommand(armed)}${intent.reason?` (rejected form: ${intent.reason})`:""}`)}throw Error("BLOCKED: PR_FEEDBACK is armed for publication; only read-only inspection, the exact approved push, and complete_pr_workflow are allowed. To change approved content, use invalidate_pr_feedback_publication (audited invalidation; the full ladder re-runs) or abort_pr_workflow with cancel_publication for a terminal no-publish cancellation")}if(!state.prHeadSha&&normalizedTool==="prepare_pr_workflow_checkout")return;if(!state.prHeadSha&&isDetachedFeedbackCheckout&&!isCanonicalReviewCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref. Other detached refs are not accepted");if(!state.prHeadSha&&isCanonicalReviewCheckout)return;if(isStandaloneGitCommitShell){await assertPrFeedbackReadyToPublish(directory,sessionID);return}if(isPublicationShell||isPublicationTool)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; finish every ordered gate, create the one approved commit, and call complete_pr_workflow before publishing");if(isShellCommandRequiringVerification){if(!state.prHeadSha&&isShellCheckout)throw Error("BLOCKED: PR_FEEDBACK checkout should use one exact local tracking branch, such as `gh pr checkout <number> --branch <local_branch>` or `git switch -c <local_branch> --track <remote>/<branch>`, before binding. If checkout is already detached at the authoritative full PR head SHA, bind it directly; the controller attaches one unambiguous exact tracking ref");throw Error("BLOCKED: PR_FEEDBACK shell commands fail closed unless they are explicit read-only intake or the one standalone approved git commit; use structured coder/write tools for fixes and run_pr_feedback_stage_a for validation")}if(!isDirectWrite&&!isShellCommandRequiringVerification&&!isRemoteMutationTool&&!isCoderTask&&normalizedTool!=="prepare_pr_feedback_scope")return;if(normalizedTool==="abort_pr_workflow")return;await assertPrFeedbackVerificationSettled(directory,sessionID)}async function readPrReviewReentryBindingContext(directory,sessionID){let state=await readPrWorkflowGateStateFromDisk3(directory,normalizeSessionID(sessionID));return state?prReviewReentryBindingFromState(directory,state):null}async function prReviewReentryBindingFromState(directory,state){if(state.mode!=="PR_REVIEW"||!state.prHeadSha)return null;let ctx=await createPrReviewGateContext2(directory,state);return{prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,generation:state.revision,...state.workflowInstanceId?{workflowInstanceId:state.workflowInstanceId}:{},...state.prReviewArtifactRunId??state.prReviewReservedRunId?{runId:state.prReviewArtifactRunId??state.prReviewReservedRunId??void 0}:{}}}async function hasActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)return!1;let binding=await prReviewReentryBindingFromState(directory,state);if(!binding)return!1;return hasPrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function reserveActivePrReviewReentryAuthorization(directory,sessionID,request){let normalizedSessionID=normalizeSessionID(sessionID);return withSessionStateMutation(directory,normalizedSessionID,async()=>{let state=await readPrWorkflowGateStateFromDisk3(directory,normalizedSessionID);if(!state)return null;let binding=await prReviewReentryBindingFromState(directory,state);if(!binding)return null;return await _test_exports2.beforePrReviewReentryReservation?.(),reservePrReviewReentryAuthorizationAgainstBinding(directory,normalizedSessionID,request,binding)})}async function completePrWorkflow(directory,sessionID,expectedMode,prHeadSha,options){let state=await requireBoundState2(directory,sessionID,expectedMode),normalizedHead=normalizePrHeadSha(prHeadSha);if(state.prHeadSha!==normalizedHead)throw Error(`BLOCKED: cannot complete ${expectedMode} at PR head "${normalizedHead}"; workflow is bound to "${state.prHeadSha}"`);let laneSettlement=await settlePresumedStalePrWorkflowLanes(directory,state.sessionID,options?.laneLiveness);if(laneSettlement.openLanes>0)throw Error(`BLOCKED: ${expectedMode} completion has ${laneSettlement.openLanes} unsettled PR workflow lane(s)`+describePrWorkflowLaneProbe(laneSettlement));let terminalClearRevision;if(expectedMode==="PR_REVIEW"){let verdict=options?.reportVerdict;if(verdict===void 0)throw Error("BLOCKED: PR_REVIEW completion requires a terminal report_verdict (APPROVE, REQUEST_CHANGES, or INCOMPLETE)");let ctx=await createPrReviewGateContext2(directory,state),settlement=derivePrReviewDimensionSettlement(directory,state,ctx.revisionDigest),dispatchCoverageFinalization=(finalizationSettlement)=>{let outcome=reducePrReviewEvent(state,{type:"coverage_finalization_requested",settlement:{kind:finalizationSettlement.kind,coveredDimensions:finalizationSettlement.coveredDimensions,unresolvedDimensions:finalizationSettlement.unresolvedDimensions,liveDimensions:finalizationSettlement.liveDimensions},requestedVerdict:verdict});if(outcome.status==="applied")return;let{code}=outcome.rejection;if(code==="live_lane_blocks_coverage"){if(finalizationSettlement.kind==="NO_COVERAGE")throw Error(`BLOCKED: PR_REVIEW completion has zero covered dimensions and still-live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Collect or settle them, then complete with report_verdict INCOMPLETE.`);throw Error(`BLOCKED: PR_REVIEW base coverage is incomplete and still has live lanes for: ${finalizationSettlement.liveDimensions.join(", ")}. Completion is allowed only once every launched lane is terminal or explicitly cancelled.`)}if(code==="no_coverage_requires_incomplete")throw Error(`BLOCKED: PR_REVIEW NO_COVERAGE completion must report verdict INCOMPLETE; got "${verdict}". A zero-coverage report never approves and never claims a code-quality review.`);let allowedList=allowedPrReviewReportVerdicts(finalizationSettlement.kind).join(" | ");throw Error(`BLOCKED: PR_REVIEW ${finalizationSettlement.kind} completion allows report_verdict ${allowedList}; got "${verdict}". Partial coverage never approves and never claims a full review.`)};if(dispatchCoverageFinalization(settlement),settlement.kind==="NO_COVERAGE"){let noCoverageRunId=state.prReviewArtifactRunId??state.prReviewReservedRunId??generatePrReviewRunId();terminalClearRevision=(await admitPrReviewPartialBaseCoverage2(directory,sessionID,noCoverageRunId,settlement.unresolvedDimensions.map((entry)=>entry.dimension))).revision;try{appendCoreEventSync(directory,{type:"pr_review_no_coverage_terminal",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,revisionDigest:ctx.revisionDigest,coveredDimensions:settlement.coveredDimensions.length,unresolvedDimensions:settlement.unresolvedDimensions.map((entry)=>`${entry.dimension}:${entry.terminalState}`),disclosureRunId:noCoverageRunId,reportVerdict:verdict})}catch{}}else{let ready=await assertPrReviewTerminalReady(directory,sessionID,options?.laneLiveness),readyState=ready.state;if(workflowIdentity(readyState)!==workflowIdentity(state)||readyState.revision!==state.revision)throw Error("BLOCKED: PR_REVIEW state changed while checking terminal readiness; retry from current state");dispatchCoverageFinalization(ready.settlement)}}else{await ensurePublicationGenerationCurrent(directory,sessionID);let readyState=await assertPrFeedbackReadyToPublish(directory,sessionID);readyState=await reconcileForeignInFlightAttempt(directory,sessionID)??readyState;let currentDigest=await currentPrFeedbackRevisionDigest(directory,readyState),armed=readyState.prFeedbackReadyToPublish;if(!armed){let previousActive=readyState.prFeedbackPublication?.active;if(previousActive?.state==="published"){if((await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,previousActive.remoteName,previousActive.remoteBranchRef))?.toLowerCase()!==previousActive.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK generation ${previousActive.generation} is marked published but the remote verification no longer holds; inspect pr_workflow_status`);return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"completed"}let localHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim();if(!localHead)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a verified local Git HEAD");let commitCount=await _test_exports2.resolveCommitCountSinceAsync(directory,state.prHeadSha,localHead);if(commitCount===0){if(localHead!==state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires HEAD to equal the immutable intake head (history diverged; resolve it or rebind via rebind_pr_feedback_head)");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK zero-descendant completion requires a clean index and working tree");let classifications=readLegacySettledFeedbackClassifications(directory,readyState),inventory=readyState.prFeedbackInventory??[],offenders=inventory.filter((itemId)=>!classifications.has(itemId)||!FEEDBACK_NO_CHANGE_CLASSIFICATIONS.has(classifications.get(itemId)));if(offenders.length>0)throw Error(`BLOCKED: PR_FEEDBACK zero-commit completion requires every inventory item verified as a no-change outcome (DISPROVED, PRE_EXISTING, NEEDS_MORE_EVIDENCE, or NEEDS_USER_DECISION); offending items: ${offenders.slice(0,10).join(", ")}. Items with confirmed content changes must follow the exactly-one-reviewed-commit path.`);try{appendCoreEventSync(directory,{type:"pr_feedback_verified_no_change",timestamp:isoNow(),sessionID:state.sessionID,prHeadSha:state.prHeadSha,items:inventory.length})}catch{}if(previousActive&&previousActive.state==="invalidated")appendPublicationEvent(directory,{type:"pr_feedback_publication_cancelled",sessionID:state.sessionID,generation:previousActive.generation,reason:"verified-no-change-terminal"});return await clearPrWorkflowGateState(directory,sessionID,readyState.revision),"verified-no-change"}if(commitCount!==1)throw Error("BLOCKED: PR_FEEDBACK publication requires exactly one descendant commit after the immutable intake head");if(await _test_exports2.resolveIsExactSingleChildCommitAsync(directory,state.prHeadSha,localHead)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication commit must be a non-merge direct child of the immutable intake head");if(await _test_exports2.resolveIsWorkingTreeCleanAsync(directory)!==!0)throw Error("BLOCKED: PR_FEEDBACK publication requires a clean index and working tree so all approved content is captured by the bound commit");let upstreamTarget=await _test_exports2.resolveCurrentUpstreamPushTargetAsync(directory);if(!upstreamTarget)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a current branch bound to an exact remote name, remote branch ref, and remote-tracking ref");if(previousActive&&previousActive.state!=="invalidated")throw Error(`BLOCKED: PR_FEEDBACK cannot arm a new publication generation while generation ${previousActive.generation} is ${previousActive.state}`);let workspaceIdentity=canonicalWorkspaceIdentity(directory);if(!workspaceIdentity)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without a canonical workspace identity");let localHeadRef=await _test_exports2.resolveCurrentLocalHeadRefAsync(directory);if(!localHeadRef)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the current branch ref (HEAD appears detached)");let remoteUrlIdentity=await _test_exports2.resolveRemoteUrlIdentityAsync(directory,upstreamTarget.remoteName);if(!remoteUrlIdentity)throw Error(`BLOCKED: PR_FEEDBACK cannot arm publication without a credential-redacted remote URL identity for "${upstreamTarget.remoteName}"`);let evidenceJoin=buildPublicationEvidenceJoin(readyState,currentDigest);if(!evidenceJoin)throw Error("BLOCKED: PR_FEEDBACK cannot arm publication without the exact settled receipt set (Stage A plus one batch per ordered phase)");let armedAt=isoNow(),generation={schemaVersion:PUBLICATION_SCHEMA_VERSION,generation:(previousActive?.generation??0)+1,state:"armed",workspaceIdentity,sessionID:readyState.sessionID,prTargetUrl:readyState.prFeedbackTargetUrl,intakeHeadSha:readyState.prHeadSha??"unknown",localHeadRef,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef,remoteRef:upstreamTarget.remoteTrackingRef,revisionDigest:currentDigest,evidence:evidenceJoin,createdAt:armedAt,armedAt};return await persistState2(directory,{...readyState,updatedAt:armedAt,prFeedbackReadyToPublish:deriveReadyToPublishMirror(generation),prFeedbackPublication:nextPublicationContainer(readyState.prFeedbackPublication,generation,previousActive?[{...previousActive,supersededByGeneration:generation.generation}]:[],[])}),appendPublicationEvent(directory,{type:"pr_feedback_publication_armed",sessionID:readyState.sessionID,generation:generation.generation,supersedes:previousActive?.generation??null,revisionDigest:currentDigest,localHead,remoteName:upstreamTarget.remoteName,remoteUrlIdentity,remoteBranchRef:upstreamTarget.remoteBranchRef}),"ready-to-publish"}let armedState=await assertPrFeedbackPublicationArmed(directory,sessionID),active=armedState.prFeedbackPublication?.active;if(!active)throw Error("BLOCKED: PR_FEEDBACK publication is not armed; call complete_pr_workflow once after every ordered gate passes");let attemptsForGeneration=(armedState.prFeedbackPublication?.attempts??[]).filter((attempt)=>attempt.generation===active.generation);if(!attemptsForGeneration.some((attempt)=>attempt.result))throw Error(`BLOCKED: PR_FEEDBACK completion requires the exact approved push to have been admitted and observed for generation ${active.generation}; run the exact push first: ${expectedBoundPushCommand(armed)}`);if(armed.revisionDigest!==currentDigest)throw Error("BLOCKED: PR_FEEDBACK publication revision differs from the independently approved content digest");let publishedHead=(await _test_exports2.resolveCurrentGitHeadAsync(directory))?.trim(),remoteRefs=publishedHead?await _test_exports2.resolveRemoteRefsContainingHeadAsync(directory,publishedHead):null,remoteHead=await _test_exports2.resolveExactRemoteBranchHeadAsync(directory,armed.remoteName,armed.remoteBranchRef);if(!publishedHead||publishedHead!==armed.localHead||!remoteRefs?.includes(armed.remoteRef)||remoteHead?.toLowerCase()!==armed.localHead.toLowerCase())throw Error(`BLOCKED: PR_FEEDBACK completion requires approved commit ${armed.localHead} at current Git HEAD and intended remote-tracking ref ${armed.remoteRef} at that exact commit`);let publishedAt=isoNow(),published={...active,state:"published",publishedAt},publishState={...armedState,updatedAt:publishedAt,prFeedbackReadyToPublish:void 0,prFeedbackPublication:nextPublicationContainer(armedState.prFeedbackPublication,published)};return await persistState2(directory,publishState),appendPublicationEvent(directory,{type:"pr_feedback_published",sessionID:armedState.sessionID,generation:published.generation,localHead:published.localHead,remoteName:published.remoteName,remoteBranchRef:published.remoteBranchRef,remoteUrlIdentity:published.remoteUrlIdentity??null,revisionDigest:published.revisionDigest,attempts:attemptsForGeneration.length}),await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,publishState.revision),"completed"}return await _test_exports2.beforeTerminalClear?.(),await clearPrWorkflowGateState(directory,sessionID,terminalClearRevision??state.revision),"completed"}function noActiveGateError(sessionID){return Error(`BLOCKED: no active PR workflow gate for session "${normalizeSessionID(sessionID)}". The gate is activated by running \`/swarm pr-review <pr-ref>\` (PR_REVIEW) or \`/swarm pr-feedback <pr-ref>\` (PR_FEEDBACK), or by the first dispatch_lanes_async call with mode "swarm-pr-review:*" / "swarm-pr-feedback:*".`)}async function requireAnyActiveState(directory,sessionID){let state=await readPrWorkflowGateState(directory,sessionID);if(!state)throw noActiveGateError(sessionID);return state}async function requireBoundState2(directory,sessionID,expectedMode){let state=await requireAnyActiveState(directory,sessionID);if(state.mode!==expectedMode)throw wrongModeError(state,expectedMode);if(!state.prHeadSha)throw Error(`BLOCKED: active ${expectedMode} workflow is not bound to a PR head`);if(expectedMode==="PR_REVIEW")await assertCurrentCheckoutHead(directory,state.prHeadSha,"PR_REVIEW"),await assertPrReviewCleanCheckout(directory);return state}function wrongModeError(state,expectedMode){return Error(`BLOCKED: session "${state.sessionID}" is active in ${state.mode}, not ${expectedMode}`)}function normalizeWorkflowLanes(lanes){if(!Array.isArray(lanes)||lanes.length===0)throw Error("BLOCKED: PR workflow lane validation requires at least one lane");let normalized=lanes.map((lane)=>{let workflowLane=lane.workflowLane?.trim(),laneId=lane.laneId?.trim()||workflowLane;if(!workflowLane||!laneId)throw Error("BLOCKED: PR workflow lane validation requires every lane to have non-empty laneId and workflow_lane values");let reviewItemIds=lane.reviewItemIds?.map((itemId)=>itemId.trim());if(reviewItemIds?.some((itemId)=>!itemId))throw Error("BLOCKED: PR workflow review_item_ids must not contain empty values");if(reviewItemIds){if(reviewItemIds.length>MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS)throw Error(`BLOCKED: PR workflow review_item_ids may not exceed ${MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS} entries`);assertNoDuplicates(reviewItemIds,"review item ids within one lane")}let ownedWorkflowLanes=lane.ownedWorkflowLanes?.map((owned)=>owned.trim());if(ownedWorkflowLanes){if(ownedWorkflowLanes.some((owned)=>!owned))throw Error("BLOCKED: PR workflow owned_workflow_lanes must not contain empty values");if(assertNoDuplicates(ownedWorkflowLanes,"owned workflow lanes within one lane"),!ownedWorkflowLanes.includes(workflowLane))throw Error(`BLOCKED: PR workflow lane "${laneId}" must include its own workflow_lane "${workflowLane}" in owned_workflow_lanes`)}return{laneId,workflowLane,...reviewItemIds?{reviewItemIds}:{},...ownedWorkflowLanes?{ownedWorkflowLanes}:{}}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"lane ids"),assertNoDuplicates(normalized.map((lane)=>lane.workflowLane),"workflow lane ids"),assertNoDuplicates(normalized.flatMap((lane)=>lane.ownedWorkflowLanes??[lane.workflowLane]),"owned workflow lane ids across lanes"),normalized}function normalizeInventoryIds(inventoryIds){if(!Array.isArray(inventoryIds)||inventoryIds.length===0)throw Error("BLOCKED: PR_FEEDBACK inventory declaration requires at least one feedback item id");let normalized=inventoryIds.map((inventoryId)=>{let itemId=inventoryId.trim();if(!itemId)throw Error("BLOCKED: PR_FEEDBACK inventory declaration contains an empty item id");return itemId});return assertNoDuplicates(normalized,"inventory item ids"),normalized.sort()}function normalizeOwnership(ownership){if(!Array.isArray(ownership)||ownership.length===0)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires at least one lane declaration");let normalized=ownership.map((lane)=>{let laneId=lane.laneId?.trim();if(!laneId)throw Error("BLOCKED: PR_FEEDBACK verification ownership requires every lane to have a non-empty laneId");let ownedItemIds=normalizeInventoryIds(lane.ownedItemIds);return{laneId,ownedItemIds}});return assertNoDuplicates(normalized.map((lane)=>lane.laneId),"PR_FEEDBACK verification lane ids"),normalized}function assertNoDuplicates(values,label){let seen=new Set;for(let value of values){if(seen.has(value))throw Error(`BLOCKED: duplicate ${label} are not allowed: ${value}`);seen.add(value)}}function containsProtectedWorkflowPath(value){return/(?:^|[^A-Za-z0-9_.-])\.swarm(?:[\\/]|$)/i.test(value.replace(/\\\\/g,"\\"))}function isPrWorkflowControllerTool(mode,toolName){if(PR_WORKFLOW_SHARED_CONTROLLER_TOOLS.has(toolName))return!0;return mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS.has(toolName):PR_FEEDBACK_CONTROLLER_TOOLS.has(toolName)}function describePrWorkflowControllerToolNames(mode){let modeTools=mode==="PR_REVIEW"?PR_REVIEW_CONTROLLER_TOOLS:PR_FEEDBACK_CONTROLLER_TOOLS,names=[...PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,...modeTools].sort((a,b)=>a.localeCompare(b));return` Allowed controller tools for ${mode}: ${names.join(", ")}. Observe current state read-only with the pr_workflow_status tool.`}function isTrustedPrWorkflowToolInvocationSafe(toolName,args2){if(toolName==="lint")return args2.mode==="check";if(toolName==="sast_scan")return args2.capture_baseline!==!0;return!0}function isAllowedPrReviewReadOnlyToolName(toolName){if(PR_REVIEW_READ_ONLY_TOOL_NAMES.has(toolName))return!0;let tokens=toolName.split(/[._:/-]+/).filter(Boolean);if(tokens.some((token)=>/^(?:add|alter|and|append|apply|approve|cancel|checkout|close|comment|commit|convert|create|delete|destroy|dismiss|drop|edit|execute|grant|insert|mark|merge|move|patch|prepend|publish|push|ready|remove|rename|replace|resolve|rerun|revoke|run|send|submit|then|transfer|truncate|unresolve|update|upload|write)$/i.test(token)))return!1;return tokens.some((token)=>/^(?:check|checks|diff|fetch|find|get|glob|grep|hover|inspect|list|lookup|open|read|references|scan|screenshot|search|show|status|symbols|tree|view)$/i.test(token))}function unsafeReadOnlyArgument(path99,constraint,value){return{safe:!1,path:path99||"(root)",constraint,value}}function readOnlyArgumentPath(parent,key2){return parent?`${parent}.${key2}`:key2}function classifyReadOnlyToolArguments(toolName,value,key2="",path99="",depth=0){if(depth>8)return unsafeReadOnlyArgument(path99,"argument nesting exceeds the read-only depth limit of 8",value);let keyTokens=key2.replace(/([a-z0-9])([A-Z])/g,"$1_$2").split(/[._:/-]+/).filter(Boolean);if(keyTokens.some((token)=>/^(?:append|body|content|create|data|delete|destination|destroy|edit|insert|mutation|output|patch|payload|prepend|remove|replace|save|set|truncate|update|upload|write)$/i.test(token)))return unsafeReadOnlyArgument(path99,"argument name is mutation-bearing and is not allowed for read-only tools",value);if(keyTokens.some((token)=>/^(?:method|verb)$/i.test(token)))return typeof value==="string"&&/^(?:GET|HEAD)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,"HTTP method/verb must be GET or HEAD for a read-only tool",value);if(keyTokens.length===1&&keyTokens.some((token)=>/^(?:action|operation)$/i.test(token)))return typeof value==="string"&&/^(?:check|diff|fetch|find|get|inspect|list|lookup|open|read|scan|search|show|status|view)$/i.test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,"action/operation must name a recognized observation operation",value);if(/^mode$/i.test(key2)&&typeof value==="string")return(toolName==="search"?/^(?:r|rb|read|literal|regex)$/i:/^(?:r|rb|read)$/i).test(value.trim())?{safe:!0}:unsafeReadOnlyArgument(path99,toolName==="search"?"search mode must be one of r, rb, read, literal, or regex":"mode must be one of r, rb, or read for a read-only tool",value);if(typeof value==="string"){if(keyTokens.some((token)=>/^(?:query|request|sql|statement)$/i.test(token))&&/(?:\b(?:alter|call|comment|create|delete|drop|exec(?:ute)?|grant|insert|merge|mutation|replace|revoke|truncate|update|upsert)\b|\bselect\b[\s\S]{0,4000}\binto\s+[A-Za-z_"'`])/i.test(value))return unsafeReadOnlyArgument(path99,"query/request text contains a mutating operation",value);return/(?:^(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE|write|edit|patch|create|delete|destroy|remove|replace|truncate|update|upload)$|(?:^|[\r\n])\s*(?:POST|PUT|PATCH|DELETE|CONNECT|TRACE)\s+\S+(?:\s+HTTP\/\d(?:\.\d)?)?|\bmutation\b|\b(?:create|drop|alter|truncate)\s+(?:or\s+replace\s+)?(?:table|database|schema|index|view|function|procedure|trigger|sequence)\b|\b(?:delete\s+from|insert\s+into|merge\s+into|replace\s+into|upsert\s+into)\b|\bupdate\s+[A-Za-z0-9_."'`-]+(?:\s+(?:AS\s+)?[A-Za-z0-9_"'`-]+)?\s+set\b|\b(?:grant|revoke)\s+\S+\s+(?:on|from|to)\b|\b(?:call|exec(?:ute)?)\s+[A-Za-z0-9_."'`-]+|\b(?:rm|rmdir|del|remove-item|move-item|set-content|add-content)\b)/i.test(value)?unsafeReadOnlyArgument(path99,"string value contains a mutating command or request",value):{safe:!0}}if(value===null||value===void 0||typeof value==="number"||typeof value==="boolean")return{safe:!0};if(Array.isArray(value)){for(let index=0;index<value.length;index++){let result=classifyReadOnlyToolArguments(toolName,value[index],key2,`${path99}[${index}]`,depth+1);if(!result.safe)return result}return{safe:!0}}if(typeof value==="object"){for(let[childKey,childValue]of Object.entries(value)){let result=classifyReadOnlyToolArguments(toolName,childValue,childKey,readOnlyArgumentPath(path99,childKey),depth+1);if(!result.safe)return result}return{safe:!0}}return unsafeReadOnlyArgument(path99,"argument type is not supported by the read-only classifier",value)}function normalizePrWorkflowShellCommand(command){let normalized=command.trim(),withoutTrailingMerge=normalized.replace(PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,"");if(withoutTrailingMerge!==normalized)normalized=withoutTrailingMerge.trim();let strippedCdPrefix=!1;for(let index=0;index<PR_WORKFLOW_MAX_CD_PREFIX_STRIPS;index+=1){let next=normalized.replace(PR_WORKFLOW_CD_PREFIX_PATTERN,"");if(next===normalized)break;normalized=next.trim(),strippedCdPrefix=!0}return{normalized,strippedCdPrefix}}function isAllowedPrWorkflowReadOnlyShell(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," ");if(!normalized)return!1;if(hasUnsafeShellControlSyntax(command))return!1;if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))return!1;let gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN);if(gitMatch?.[1]){if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))return!1;return isAllowedPrWorkflowGitIntake(gitMatch[1],options)}if(/^gh /i.test(normalized))return isAllowedPrFeedbackGhIntake(normalized);if(/^rg\b/i.test(normalized)&&/\s--pre(?:-glob)?(?:\s|=|$)/i.test(normalized))return!1;return/^(?:rg|grep|cat|Get-Content|Select-String|Test-Path|Get-ChildItem|ls|dir|pwd|which|where)(?:\s|$)/i.test(normalized)}function describeBlockedPrReviewShellCommand(command,options){let{normalized:inner,strippedCdPrefix}=normalizePrWorkflowShellCommand(command),normalized=inner.replace(/\s+/g," "),gitMatch=normalized.match(PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN),pointer=" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool.",detail,syntaxViolation=describeShellSyntaxViolation(command);if(syntaxViolation)detail=syntaxViolation;else if(strippedCdPrefix&&(/^git (?:fetch|checkout|switch|branch)(?:\s|$)/i.test(normalized)||/^gh pr checkout(?:\s|$)/i.test(normalized)))detail="Reason: cd-prefix-on-checkout-verb. Run fetch/checkout/switch/branch or `gh pr checkout` bare, with no `cd <dir> &&` prefix.";else if(PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN.test(normalized)&&gitMatch?.[1]&&/^(?:fetch|checkout|switch|branch)(?:\s|$)/i.test(gitMatch[1]))detail="Reason: git -C on a state transition. Run fetch/checkout/switch/branch from the target directory, not via `git -C <dir>`.";else if(!options.allowFetch&&gitMatch?.[1]&&/^fetch(?:\s|$)/i.test(gitMatch[1]))detail=options.allowTrackingFetch?"Reason: bound-fetch-restriction. After the PR head is bound only the exact bound remote-tracking fetch is allowed; read remote state via gh_evidence otherwise.":"Reason: bound-fetch-restriction. Fetch is not permitted in this bound state; read remote state via gh_evidence instead.";else if(gitMatch?.[1]||/^git(?:\s|$)/i.test(normalized))detail="Reason: unlisted git verb. Allowed git reads: status/log/show/diff/rev-parse/merge-base/ls-files/grep/blame/cat-file/for-each-ref, `branch` with listing flags only, `stash list`, `worktree list`, `remote -v`, `config --get`.";else if(/^gh(?:\s|$)/i.test(normalized))detail="Reason: unlisted gh form. Allowed gh reads: pr view/diff/checks/status/list, run view/list/watch, issue view/list, search, api GET. If gh is missing, fetch the api.github.com REST URL with the web fetch tool.";else detail="Reason: unlisted binary. Allowed: rg/grep/cat/ls/dir/pwd/which/where plus read-only git/gh intake.";return detail+" Observe HEAD/branch/dirty/remotes/gate state read-only with the pr_workflow_status tool."}function classifyPrWorkflowShellSyntax(command){let{normalized:inner}=normalizePrWorkflowShellCommand(command),compact=inner.replace(/\s+/g," ").trim();if(!compact)return{unsafe:!0,reason:"compound-syntax"};if(/\$\(|@\(/.test(inner))return{unsafe:!0,reason:"command-substitution"};if(/\\"|\^"/.test(inner))return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(/[\r\n;&<>`]/.test(inner))return{unsafe:!0,reason:"compound-syntax"};let tokens=[],current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0,flush=()=>{if(current.length>0||quoted2)tokens.push({value:current,quoted:quoted2,pipeIsDoubleQuoted});current="",quoted2=!1,quote=null,pipeIsDoubleQuoted=!0};for(let index=0;index<inner.length;index+=1){let ch=inner[index];if(quote===null){if(/\s/.test(ch)){flush();continue}if(ch==="'"||ch==='"'){quoted2=!0,quote=ch;continue}if(ch===";"||ch==="<"||ch===">"||ch==="`"||ch==="|")return{unsafe:!0,reason:"compound-syntax"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch;continue}if(quote==="'"){if(ch==="'"){quote=null;continue}if(ch==="|")pipeIsDoubleQuoted=!1;current+=ch;continue}if(ch==='"'){quote=null;continue}if(ch==="\\"&&inner[index+1]==='"')return{unsafe:!0,reason:"ambiguous-escaped-quote"};if(ch==="`")return{unsafe:!0,reason:"command-substitution"};if(ch==="$"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};if(ch==="@"&&inner[index+1]==="(")return{unsafe:!0,reason:"command-substitution"};current+=ch}if(quote!==null)return{unsafe:!0,reason:"unmatched-quote"};flush();let pipeTokens=tokens.filter((token)=>token.value.includes("|"));if(pipeTokens.length===0)return{unsafe:!1,reason:null};if(pipeTokens.length!==1||!pipeTokens[0].quoted||!pipeTokens[0].pipeIsDoubleQuoted)return{unsafe:!0,reason:"gh-api-jq-pipe"};let quotedPipeToken=pipeTokens[0];if(!/^gh\s+api(?:\s|$)/i.test(compact))return{unsafe:!0,reason:"gh-api-jq-pipe"};for(let index=0;index<tokens.length;index+=1)if(tokens[index].value==="--jq"&&tokens[index+1]===quotedPipeToken)return{unsafe:!1,reason:null};return{unsafe:!0,reason:"gh-api-jq-pipe"}}function hasUnsafeShellControlSyntax(command){return classifyPrWorkflowShellSyntax(command).unsafe}function describeShellSyntaxViolation(command){let verdict=classifyPrWorkflowShellSyntax(command);if(!verdict.unsafe)return null;switch(verdict.reason){case"unmatched-quote":return"Reason: unmatched quote in the shell command. Close the quote and retry with a single read-only command.";case"ambiguous-escaped-quote":return"Reason: backslash- or caret-escaped double quotes are ambiguous across cmd.exe, PowerShell, and POSIX shells. Use a jq filter that needs no nested double quotes, or use the bounded gh_evidence tool.";case"command-substitution":return"Reason: command-substitution syntax ($() or @()) is not allowed in this read-only gate.";case"gh-api-jq-pipe":return"Reason: literal `|` is only allowed inside a double-quoted `gh api --jq` value; single quotes do not protect pipes under cmd.exe, and every other shape is treated as compound shell syntax.";default:return"Reason: compound-syntax (;, &&, |, <, >, backtick, or $()/@()). Run ONE command per call; a single leading `cd <dir> &&` and a trailing `2>&1` are tolerated for reads only."}}function isSafeStandaloneGitCommit(command){if(hasUnsafeShellControlSyntax(command))return!1;if(/(?:^|\s)--(?:allow-empty|amend)(?:\s|=|$)/i.test(command))return!1;return/^[Gg][Ii][Tt](?:\s+-C(?:=|\s+)(?:"[^"\r\n]+"|'[^'\r\n]+'|[^\s;&|<>`]+))?\s+commit(?:\s+(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s;&|<>`]+))*\s*$/.test(command.trim())}function boundPushTarget(armed){let remote=armed.remoteName,branch=armed.remoteBranchRef.slice(11);if(!armed.remoteBranchRef.startsWith("refs/heads/")||!branch)return null;if(/\s|[;&|<>`]/.test(remote)||/\s|[;&|<>`]/.test(branch))return null;return{remote,branch}}function expectedBoundPushCommand(armed){let target=boundPushTarget(armed);return target?`git push ${target.remote} ${armed.localHead}:refs/heads/${target.branch}`:"(invalid bound remote-tracking ref; restart the workflow)"}function isAllowedPrWorkflowGitIntake(gitArgs,options){if(/(?:--ext-diff|--textconv|--open-files-in-pager|--output(?:=|\s)|--upload-pack(?:=|\s)|--exec(?:=|\s))/i.test(gitArgs))return!1;if(/^(?:status|log|show|diff|rev-parse|merge-base|ls-files|grep|blame|cat-file|for-each-ref|--version|version)(?:\s|$)/i.test(gitArgs))return!0;if(isAllowedReadOnlyGitBranchListing(gitArgs))return!0;if(isAllowedReadOnlyGitStashListing(gitArgs))return!0;if(isAllowedReadOnlyGitWorktreeListing(gitArgs))return!0;if(options.allowFetch&&/^fetch(?:\s|$)/i.test(gitArgs))return!0;if(options.allowTrackingFetch&&isAllowedBoundRemoteTrackingFetch(gitArgs,options.trackingFetchTarget))return!0;if(/^remote(?:\s+-v)?$/i.test(gitArgs))return!0;if(options.allowCheckout&&isAllowedPreBindBranchSetup(gitArgs))return!0;if(options.allowCheckout&&/^(?:checkout|switch)\s+(?:--detach\s+)?[^\s-][^\s]*$/i.test(gitArgs))return!0;return/^config\s+(?:(?:--show-origin|--show-scope|--global|--local|--system|--worktree)\s+)*(?:--list|--get(?:-all)?\s+\S+)$/i.test(gitArgs)}function isAllowedBoundRemoteTrackingFetch(gitArgs,target){if(!target?.remoteName||!target.remoteBranchRef.startsWith("refs/heads/"))return!1;let tokens=gitArgs.trim().split(/\s+/);if(tokens.length!==3||tokens[0].toLowerCase()!=="fetch")return!1;let[,remote,remoteBranch]=tokens,expectedBranch=target.remoteBranchRef.slice(11);return isSafeGitRefToken(remote)&&!remote.includes("/")&&isSafeGitRefToken(remoteBranch)&&!remoteBranch.startsWith("-")&&!remoteBranch.includes(":")&&remote===target.remoteName&&remoteBranch===expectedBranch}function isAllowedPreBindBranchSetup(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===5){let[verb,createFlag,localBranch,trackFlag,upstream]=tokens;return(verb==="checkout"||verb==="switch")&&(createFlag==="-b"||createFlag==="-c")&&trackFlag==="--track"&&isSafeGitRefToken(localBranch)&&isSafeGitRefToken(upstream)&&upstream.includes("/")}if(tokens.length===3&&tokens[0]==="branch"){let upstream=tokens[1].match(/^--set-upstream-to=(.+)$/)?.[1];return Boolean(upstream&&isSafeGitRefToken(upstream)&&upstream.includes("/")&&isSafeGitRefToken(tokens[2]))}return!1}function isAllowedReadOnlyGitBranchListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length===0||tokens[0].toLowerCase()!=="branch")return!1;let listingSelectorInEffect=!1;for(let index=1;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:--list|--contains|--merged|--no-merged|--points-at)$/i.test(token)){listingSelectorInEffect=!0;continue}if(/^(?:-a|--all|-r|--remotes|-v|-vv|--verbose|--show-current|--color|--no-color|--column|--no-column|-i|--ignore-case)$/i.test(token)||/^--(?:sort|format|color)=/i.test(token))continue;if(token.startsWith("-"))return!1;if(!listingSelectorInEffect)return!1}return!0}function isAllowedReadOnlyGitStashListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="stash")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--oneline|--patch|-p|--stat|--color|--no-color)$/i.test(token))continue;if(/^--(?:format|pretty)=/i.test(token))continue;return!1}return!0}function isAllowedReadOnlyGitWorktreeListing(gitArgs){let tokens=gitArgs.trim().split(/\s+/);if(tokens.length<2||tokens[0].toLowerCase()!=="worktree")return!1;if(tokens[1].toLowerCase()!=="list")return!1;for(let index=2;index<tokens.length;index+=1){let token=tokens[index];if(/^(?:-v|--verbose|--porcelain|-z)$/i.test(token))continue;return!1}return!0}function isSafeGitRefToken(value){return/^[A-Za-z0-9][A-Za-z0-9._/-]*$/.test(value)&&!value.includes("..")&&!value.includes("//")&&!value.includes("@{")&&!value.endsWith("/")&&!value.endsWith(".")&&!value.endsWith(".lock")}function isAllowedPrFeedbackGhIntake(command){if(/^gh\s+pr\s+checkout(?:\s|$)/i.test(command))return isAllowedSafeGhPrCheckout(command);if(/^gh\s+--version$/i.test(command)||/^gh\s+pr\s+(?:view|diff|checks|status|list)(?:\s|$)/i.test(command)||/^gh\s+run\s+(?:view|list|watch)(?:\s|$)/i.test(command)||/^gh\s+issue\s+(?:view|list)(?:\s|$)/i.test(command)||/^gh\s+search\s+(?:code|commits|issues|prs|repos)(?:\s|$)/i.test(command)||/^gh\s+auth\s+status(?:\s|$)/i.test(command))return!0;if(!/^gh\s+api(?:\s|$)/i.test(command))return!1;if(/\bmutation\b/i.test(command))return!1;let method=command.match(/\s(?:--method(?:\s+|=)|-X(?:\s+|=)?)([A-Z]+)/i)?.[1];if(method&&method.toUpperCase()!=="GET")return!1;if(/\s(?:--input|--raw-field)(?:\s|=)/i.test(command)||/\s-F(?:\s|=|\S)/.test(command))return!1;return!/\s(?:--field|-f)(?:\s|=)(?!query=)/i.test(command)}function isAllowedSafeGhPrCheckout(command){if(/\s--(?:force|recurse-submodules)(?:\s|=|$)/i.test(command))return!1;let tokens=command.trim().split(/\s+/);if(tokens.length<4||tokens[0]!=="gh"||tokens[1]!=="pr"||tokens[2]!=="checkout")return!1;let target=tokens[3];if(!/^\d+$/.test(target)&&!/^https:\/\/github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+\/pull\/\d+$/.test(target))return!1;for(let index=4;index<tokens.length;index+=1){let token=tokens[index],repoEquals=token.match(/^--repo=(.+)$/)?.[1];if(repoEquals){if(!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repoEquals))return!1;continue}let branchEquals=token.match(/^--branch=(.+)$/)?.[1];if(branchEquals){if(!isSafeGitRefToken(branchEquals))return!1;continue}if(token==="--repo"||token==="-R"){let repo=tokens[++index];if(!repo||!/^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+$/.test(repo))return!1;continue}if(token==="--branch"||token==="-b"){let branch=tokens[++index];if(!branch||!isSafeGitRefToken(branch))return!1;continue}return!1}return!0}function normalizePrHeadSha(prHeadSha){let normalized=prHeadSha.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty pr_head_sha");return normalized}async function currentPrFeedbackRevisionDigest(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_FEEDBACK revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_FEEDBACK could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return resolved.digest}function describePrWorkflowRevisionDigestFailure(failure){let detail=failure.detail?` (${failure.detail})`:"";switch(failure.reason){case"file-cap":return`the changed-file snapshot exceeded REVISION_MAX_FILES${detail}. Reduce the changed-path count (commit or stash generated/vendored output) before retrying`;case"byte-cap":return`the changed-file snapshot exceeded REVISION_MAX_TOTAL_BYTES${detail}. Reduce the changed content size before retrying`;case"buffer-truncated":return`a bounded git enumeration exceeded GIT_SNAPSHOT_MAX_BUFFER${detail}. The changed-path list is too large to enumerate`;case"timeout":return`a bounded git enumeration timed out${detail}. Retry once the working tree is quiescent`;case"git-failed":return`a bounded git enumeration failed${detail}. Verify the checkout is a healthy Git worktree at the recorded head`;case"containment":return`git reported a changed path outside the project root${detail}. Nothing outside the project root may be hashed`;case"read-failed":return`a changed path could not be read${detail}. Resolve the filesystem error before retrying`;default:return`an injected revision-digest seam returned no digest${detail}; production names one of REVISION_MAX_FILES / REVISION_MAX_TOTAL_BYTES / GIT_SNAPSHOT_MAX_BUFFER, a bounded git enumeration timeout, or a read failure`}}async function resolvePrWorkflowRevisionDigestForGate(directory,baseHeadSha){if(_test_exports2.resolvePrWorkflowRevisionDigestDetailed!==resolvePrWorkflowRevisionDigestDetailed)return _test_exports2.resolvePrWorkflowRevisionDigestDetailed(directory,baseHeadSha);if(_test_exports2.resolvePrWorkflowRevisionDigest!==resolvePrWorkflowRevisionDigest){let digest3=_test_exports2.resolvePrWorkflowRevisionDigest(directory,baseHeadSha);return digest3?{ok:!0,digest:digest3}:{ok:!1,reason:"seam-unavailable"}}return resolvePrWorkflowRevisionDigestDetailedAsync(directory,baseHeadSha)}async function createPrReviewGateContext2(directory,state){if(!state.prHeadSha)throw Error("BLOCKED: PR_REVIEW revision binding requires pr_head_sha");let resolved=await resolvePrWorkflowRevisionDigestForGate(directory,state.prHeadSha);if(!resolved.ok)throw Error(`BLOCKED: PR_REVIEW could not compute a bounded current-revision digest for pr_head_sha "${state.prHeadSha}"; ${describePrWorkflowRevisionDigestFailure(resolved)}`);return{revisionDigest:resolved.digest}}function normalizeBatchId(batchId){let normalized=batchId.trim();if(!normalized)throw Error("BLOCKED: PR workflow requires a non-empty batch id");return normalized}function sameStringArray(left,right){return left.length===right.length&&left.every((value,index)=>value===right[index])}function sameStringSet(left,right){let leftSet=new Set(left),rightSet=new Set(right);return leftSet.size===rightSet.size&&[...leftSet].every((v)=>rightSet.has(v))}function assertStringSetSubset(actual,expected,label){let actualSet=new Set(actual),expectedSet=new Set(expected),extra=[...actualSet].filter((value)=>!expectedSet.has(value));if(actual.length===0||actual.length!==actualSet.size||extra.length>0)throw Error(`BLOCKED: ${label} must be a non-empty subset of the mechanically derived inventory; extra: ${extra.join(", ")||"(none)"}`)}function derivePrReviewCandidateInventory2(directory,state,ctx){if(ctx.candidateInventory)return ctx.candidateInventory;let sources=[],baseDimensionSources=new Map,baseSourceCreditedDimensions=new Map,baseSourceFullOwnershipCount=new Map,reversedBaseBatches=[...state.prReviewBaseDispatches??[]].reverse(),successfulByBaseBatchId=new Map;for(let batch of reversedBaseBatches)successfulByBaseBatchId.set(batch.batchId,successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:base",batch.validatedAt,!0,new Set,ctx.revisionDigest));let laneClassPasses=(state.prReviewDepthTier??"L")==="L"?[(ownedCount)=>ownedCount===1,(ownedCount)=>ownedCount!==1]:[()=>!0];for(let laneIsInClass of laneClassPasses)for(let batch of reversedBaseBatches){let successful2=successfulByBaseBatchId.get(batch.batchId)??new Set;for(let lane of batch.lanes){let ownedDimensions=lane.ownedWorkflowLanes?.length?lane.ownedWorkflowLanes:[lane.workflowLane];if(!laneIsInClass(ownedDimensions.length))continue;let creditedDimensions=ownedDimensions.filter((dimension)=>successful2.has(dimension));if(creditedDimensions.length===0)continue;let key2=`${batch.batchId}\x00${lane.laneId}`;baseSourceFullOwnershipCount.set(key2,ownedDimensions.length);for(let dimension of creditedDimensions)if(!baseDimensionSources.has(dimension)){baseDimensionSources.set(dimension,{batchId:batch.batchId,laneId:lane.laneId});let credited=baseSourceCreditedDimensions.get(key2);if(credited)credited.push(dimension);else baseSourceCreditedDimensions.set(key2,[dimension])}}}let seenBaseSourceKeys=new Set;for(let{batchId,laneId}of baseDimensionSources.values()){let key2=`${batchId}\x00${laneId}`;if(seenBaseSourceKeys.has(key2))continue;seenBaseSourceKeys.add(key2);let credited=baseSourceCreditedDimensions.get(key2),fullOwnershipCount=baseSourceFullOwnershipCount.get(key2)??0;sources.push({batchId,laneId,mode:"swarm-pr-review:base",creditedLanes:credited&&credited.length<fullOwnershipCount?credited:void 0})}let selectedCouncilLanes=new Set;if(state.prReviewTriggerEvalPath)for(let batch of[...state.prReviewValidationBatches??[]].reverse()){if(batch.phase!=="council")continue;let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,"swarm-pr-review:council",batch.validatedAt,!0,new Set,ctx.revisionDigest);for(let lane of batch.lanes)if(successful2.has(lane.workflowLane)&&!selectedCouncilLanes.has(lane.workflowLane))sources.push({batchId:batch.batchId,laneId:lane.laneId,mode:"swarm-pr-review:council"}),selectedCouncilLanes.add(lane.workflowLane)}let degradedSourceKeys=new Set;if(state.prReviewTriggerEvalPath){let triggerPath=validateSwarmPath(directory,state.prReviewTriggerEvalPath),triggerArtifact;try{let triggerStat=statSync36(triggerPath);if(!triggerStat.isFile()||triggerStat.size>PR_REVIEW_TRIGGER_RECEIPT_MAX_BYTES)throw Error("trigger evaluation artifact exceeds its read bound");triggerArtifact=JSON.parse(readFileSync37(triggerPath,"utf-8"))}catch{throw Error("BLOCKED: PR_REVIEW trigger evaluation artifact is missing or invalid")}let receipt;try{receipt=parsePrReviewTriggerReceipt(triggerArtifact)}catch(error49){throw Error(`BLOCKED: PR_REVIEW trigger evaluation is invalid: ${error49 instanceof Error?error49.message:String(error49)}`)}for(let row of receipt.matchedRows)sources.push({batchId:row.source_batch_id,laneId:row.source_lane_id,mode:"swarm-pr-review:micro",workflowLane:row.trigger_id});for(let degradation of receipt.coverageDegradations)degradedSourceKeys.add(`${degradation.source_batch_id}\x00${degradation.source_lane_id}`)}let candidateIds=[],candidateSeverities=new Map,extractedLaneKeys=new Set;for(let source of sources){let resolvedArtifact=!1;for(let record2 of findByBatchId(directory,source.batchId,{parentSessionId:state.sessionID})){if(record2.laneId!==source.laneId||record2.mode!==source.mode||record2.workspace?.prHeadSha!==state.prHeadSha||record2.workspace?.gitHead!==state.prHeadSha)continue;let structured=record2.result?.prReviewResultReceipt;if(structured){let credited=source.creditedLanes?.length?structured.envelope.creditedLanes.filter((lane)=>source.creditedLanes?.includes(lane)):structured.envelope.creditedLanes;if(source.workflowLane&&!credited.includes(source.workflowLane))continue;resolvedArtifact=!0;let laneKey2=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey2)){extractedLaneKeys.add(laneKey2);for(let finding of structured.envelope.findings){if(!credited.includes(finding.workflowLane))continue;if(candidateIds.push(finding.id),!candidateSeverities.has(finding.id))candidateSeverities.set(finding.id,finding.severity)}}continue}let ref=record2.result?.outputRef?.trim(),artifact=ref?readLaneOutput(directory,ref)?.artifact:void 0,recordOwnedLanes=record2.ownedWorkflowLanes?.length?record2.ownedWorkflowLanes:record2.workflowLane?[record2.workflowLane]:void 0;if(!artifact||!workflowArtifactHasContractMarker(directory,state,record2,source.mode,record2.workflowLane??source.workflowLane??source.laneId,void 0,ctx.revisionDigest,recordOwnedLanes))continue;if(source.workflowLane&&(!recordOwnedLanes?.includes(source.workflowLane)||!prReviewDiscoveryArtifactCoversLane(artifact.text,source.workflowLane,recordOwnedLanes,source.mode)))continue;resolvedArtifact=!0;let laneKey=`${source.batchId}\x00${source.laneId}`;if(!extractedLaneKeys.has(laneKey)){extractedLaneKeys.add(laneKey);let extracted=extractCandidateRows(artifact.text,resolvePrReviewRowFamily(source.workflowLane,source.mode),source.creditedLanes);for(let row of extracted)if(candidateIds.push(row.candidateId),row.severity&&!candidateSeverities.has(row.candidateId))candidateSeverities.set(row.candidateId,row.severity)}}if(source.mode==="swarm-pr-review:micro"&&!resolvedArtifact){if(degradedSourceKeys.has(`${source.batchId}\x00${source.laneId}`))continue;throw Error(`BLOCKED: PR_REVIEW mandatory micro-lane provenance is missing or invalid for ${source.workflowLane??source.laneId}`)}}return assertNoDuplicates(candidateIds,"PR_REVIEW discovery candidate ids"),ctx.candidateSeverities=candidateSeverities,ctx.candidateInventory=candidateIds.length>0?candidateIds.sort():[PR_REVIEW_CLEAN_SENTINEL_ID],ctx.candidateInventory}function appendBoundedCandidateIssue(issues,message){if(issues.length<MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1){issues.push(message.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return}if(issues.length===MAX_CANDIDATE_ISSUES_PER_ARTIFACT-1)issues.push("additional malformed candidate diagnostics omitted")}function resolvePrReviewRowFamily(workflowLane,mode){if(mode==="swarm-pr-review:base")return"base_explorer";if(mode==="swarm-pr-review:micro"||mode==="swarm-pr-review:council")return"micro_lane";return workflowLane!==void 0&&PR_REVIEW_BASE_DIMENSION_IDS.includes(workflowLane)?"base_explorer":"micro_lane"}function parseCanonicalCandidateRows(text,fallbackFamily){let rows=[],issues=[],headerFamily=null;for(let[index,line]of normalizeCandidateArtifactCached(text,fallbackFamily).text.split(/\r?\n/).entries()){let fields=splitPipeFields(line).map((field)=>field.trim()),detectedHeaderFamily=candidateHeaderFamily(fields);if(detectedHeaderFamily){headerFamily=detectedHeaderFamily;continue}let explicitMarker=fields[0]==="[CANDIDATE]",markerlessRow=headerFamily!==null&&Boolean(fields[0])&&!fields[0].startsWith("[");if(!explicitMarker&&!markerlessRow)continue;if(explicitMarker&&headerFamily===null){appendBoundedCandidateIssue(issues,`row ${index+1} field header: candidate output must begin with one exact canonical base or micro [CANDIDATE] header`);continue}let family=headerFamily??fallbackFamily,candidateFields=explicitMarker?fields.slice(1):fields,analysis=analyzeCandidateFields(candidateFields,family);if(!analysis.valid){for(let issue2 of analysis.issues)appendBoundedCandidateIssue(issues,`row ${index+1} field ${issue2.field}: ${issue2.message}`);continue}if(!analysis.candidateId||!analysis.workflowLane)continue;rows.push({candidateId:analysis.candidateId,workflowLane:analysis.workflowLane,severity:isCandidateSeverity(analysis.values.severity)?analysis.values.severity:null,evidence:candidateFields.slice(2).join("\x00"),lineNumber:index+1})}return{rows,issues}}function extractCandidateRows(text,fallbackFamily,scopeToLanes){let inScope=(lane)=>!scopeToLanes||lane!==void 0&&scopeToLanes.includes(lane);return parseCanonicalCandidateRows(text,fallbackFamily).rows.filter((row)=>inScope(row.workflowLane))}function extractCandidateIds(text,fallbackFamily,scopeToLanes){return extractCandidateRows(text,fallbackFamily,scopeToLanes).map((row)=>row.candidateId)}function derivePrReviewCandidateSeverities(directory,state,ctx){if(!ctx.candidateSeverities)derivePrReviewCandidateInventory2(directory,state,ctx);if(!ctx.candidateSeverities)throw Error("BLOCKED: PR_REVIEW candidate severity authority is unavailable for this gate context");return ctx.candidateSeverities}function prReviewPhaseWindow2(state,phase){let all=state.prReviewValidationBatches??[];if(phase==="critic")return all.filter((batch)=>batch.phase==="critic");let latestCouncilIndex=-1;for(let index=0;index<all.length;index++)if(all[index]?.phase==="council")latestCouncilIndex=index;return(latestCouncilIndex>=0?all.slice(latestCouncilIndex+1):all).filter((batch)=>batch.phase==="reviewer")}function reviewerSubagentSessionIds2(directory,state){let forbidden=new Set(state.prReviewRetiredReviewerSessionIds??[]);for(let reviewerBatch of(state.prReviewValidationBatches??[]).filter((batch)=>batch.phase==="reviewer"))for(let record2 of findByBatchId(directory,reviewerBatch.batchId,{parentSessionId:state.sessionID})){let subagentSessionId=record2.subagentSessionId?.trim();if(subagentSessionId)forbidden.add(subagentSessionId)}return forbidden}function batchMayContributeClaims2(directory,state,batch,phase,requiredInventory,forbiddenSubagentSessionIds,reviewerClaims,ctx){let coherence=state.prReviewBatchCoherence?.[batch.batchId];if(coherence)return phase==="critic"||sameStringSet(coherence.validatedInventory,requiredInventory);let declaredItems=batch.lanes.flatMap((lane)=>lane.reviewItemIds??[]);if(!sameStringSet(declaredItems,requiredInventory))return!1;let successful2=successfulObligationsFromExactBatch2(directory,state,batch.batchId,batch.lanes,`swarm-pr-review:${phase}`,batch.validatedAt,!0,forbiddenSubagentSessionIds,ctx.revisionDigest,void 0,reviewerClaims);return successful2.size===batch.lanes.length&&batch.lanes.every((lane)=>successful2.has(lane.workflowLane))}function authoritativeReviewerClaims2(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);return composed.unclaimed.length===0?composed.claims:new Map}function criticReviewerItemBindings(directory,state,lanes,ctx){let reviewerClaims=authoritativeReviewerClaims2(directory,state,ctx),bindings={};for(let itemId of lanes.flatMap((lane)=>lane.reviewItemIds??[])){let rowDigest=reviewerClaims.get(itemId)?.rowDigest;if(!rowDigest)throw Error(`BLOCKED: PR_REVIEW critic dispatch cannot bind item "${itemId}" to an authoritative reviewer verdict row`);bindings[reviewerItemBindingKey(itemId)]=rowDigest}return bindings}function derivePrReviewCriticInventory2(directory,state,ctx){return[...authoritativeReviewerVerdictsForGate(directory,state,ctx,"derivePrReviewCriticInventory").entries()].filter(([,verdict])=>prReviewFindingRequiresCritic({classification:verdict.classification,severity:verdict.severity,risk_impact:verdict.riskImpact,risk_tags:verdict.riskTags})).map(([itemId])=>itemId).sort()}function deriveLatestPrReviewCriticVerdicts(directory,state,ctx){let composed=composePrReviewPhaseVerdicts(directory,state,"critic",ctx);if(composed.unclaimed.length>0)return new Map;return new Map([...composed.claims].map(([itemId,claim])=>[itemId,{status:claim.classification,severity:claim.severity}]))}function deriveLatestPrReviewReviewerVerdicts(directory,state,ctx){return new Map([...authoritativeReviewerClaims2(directory,state,ctx)].map(([itemId,claim])=>[itemId,{classification:claim.classification,severity:claim.severity,riskImpact:claim.riskImpact,riskTags:claim.riskTags}]))}function assertSettledPhaseHasAuthoritativeVerdicts(phase,composed,authoritative,origin){if(composed.unclaimed.length>0)return;if(composed.requiredInventory.length===0)return;let missing=composed.requiredInventory.filter((itemId)=>!authoritative.has(itemId));if(missing.length===0)return;let named=missing.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=missing.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the ${phase} phase settled over ${composed.requiredInventory.length} required item(s), but its authoritative ${phase} verdict map is `+(authoritative.size===0?"EMPTY":`PARTIAL (${authoritative.size} of ${composed.requiredInventory.length} items)`)+" after successful settlement"+(phase==="reviewer"?"; an empty or partial reviewer verdict map empties the critic inventory, which silently skips the critic-coverage gate and lets CONFIRMED CRITICAL/HIGH findings ship unchallenged":"; an empty or partial critic verdict map silently drops challenges the gate already accepted")+`; missing ${phase} verdicts for: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}function authoritativeReviewerVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewReviewerVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("reviewer",composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx),verdicts,origin),verdicts}function authoritativeCriticVerdictsForGate(directory,state,ctx,origin){let verdicts=deriveLatestPrReviewCriticVerdicts(directory,state,ctx);return assertSettledPhaseHasAuthoritativeVerdicts("critic",composePrReviewPhaseVerdicts(directory,state,"critic",ctx),verdicts,origin),verdicts}function derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin){let reviewer=composePrReviewPhaseVerdicts(directory,state,"reviewer",ctx);if(reviewer.unclaimed.length>0){let named=reviewer.unclaimed.slice(0,MAX_UNCLAIMED_ITEMS_IN_MESSAGE),overflow=reviewer.unclaimed.length-named.length;throw Error(`BLOCKED: PR_REVIEW internal invariant violated at ${origin}: the critic-coverage decision requires a settled reviewer phase, but ${reviewer.unclaimed.length} reviewer item(s) lack an authenticated verdict; an unsettled reviewer phase derives an empty critic inventory, which would skip critic coverage instead of demanding it; unsettled reviewer items: ${named.join(", ")}`+(overflow>0?` (+${overflow} more)`:""))}return derivePrReviewCriticInventory2(directory,state,ctx)}function boundedLaneValidationValue(value){let rendered;try{rendered=typeof value==="string"?value:JSON.stringify(value)}catch{rendered=String(value)}let sanitized=[...rendered??String(value)].map((character)=>{let code=character.charCodeAt(0);return code<=31||code===127?" ":character}).join("").trim();return sanitized.length<=MAX_LANE_VALIDATION_VALUE_CHARS?sanitized:`${sanitized.slice(0,MAX_LANE_VALIDATION_VALUE_CHARS-1)}…`}function failedLaneValidation(predicate,expected,actual){return{ok:!1,failure:{predicate,expected:boundedLaneValidationValue(expected),actual:boundedLaneValidationValue(actual)}}}function formatPrReviewLaneValidationFailure(failure){return`predicate=${failure.predicate} expected=${JSON.stringify(failure.expected)} actual=${JSON.stringify(failure.actual)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2)}function analyzeLaneRecordResultIntegrity(args2){let{record:record2,result,expected}=args2;if(expected.checkWorkflowLane&&record2.workflowLane!==expected.workflowLane)return failedLaneValidation("record.workflow_lane",expected.workflowLane,record2.workflowLane??"(missing)");if(expected.checkWorkflowLane&&!ownedLaneSetsEqual(record2.ownedWorkflowLanes,expected.ownedWorkflowLanes))return failedLaneValidation("record.owned_workflow_lanes",expected.ownedWorkflowLanes,record2.ownedWorkflowLanes??(record2.workflowLane?[record2.workflowLane]:[]));if(record2.mode!==expected.mode)return failedLaneValidation("record.mode",expected.mode,record2.mode??"(missing)");if(record2.workspace?.prHeadSha!==expected.prHeadSha)return failedLaneValidation("record.pr_head_sha",expected.prHeadSha,record2.workspace?.prHeadSha??"(missing)");if(record2.workspace?.gitHead!==expected.gitHead)return failedLaneValidation("record.git_head",expected.gitHead,record2.workspace?.gitHead??"(missing)");if(args2.requireCompleted&&record2.status!=="completed")return failedLaneValidation("record.status","completed",record2.status);if(result?.outputDegraded===!0)return failedLaneValidation("result.output_degraded","not true",!0);if(result?.transcriptIncomplete===!0&&!args2.allowTranscriptIncompleteRecovery)return failedLaneValidation("result.transcript_incomplete","false outside discovery candidate recovery",!0);if((result?.chars??0)<=0)return failedLaneValidation("result.chars","greater than 0",result?.chars??0);if(!result?.digest?.trim())return failedLaneValidation("result.digest","non-empty digest",result?.digest??"(missing)");if(!result?.outputRef?.trim())return failedLaneValidation("result.output_ref","non-empty output ref",result?.outputRef??"(missing)");return{ok:!0}}function analyzePrReviewBatchRecordIntegrity(args2){let validatedAtMs=Date.parse(args2.validatedAt),expectedByLaneId=new Map(args2.expectedLanes.map((lane)=>[lane.laneId,lane])),batchFailure=!Number.isFinite(validatedAtMs)?failedLaneValidation("batch.validated_at","valid ISO timestamp",args2.validatedAt):expectedByLaneId.size!==args2.expectedLanes.length?failedLaneValidation("batch.expected_lane_unique","unique expected lane ids",args2.expectedLanes.map((lane)=>lane.laneId)):null,relevantRecords=args2.records.filter((record2)=>record2.laneId&&expectedByLaneId.has(record2.laneId)),recordsByLaneId=new Map,recordCountBySubagentSessionId=new Map;for(let record2 of relevantRecords){let laneRecords=recordsByLaneId.get(record2.laneId)??[];laneRecords.push(record2),recordsByLaneId.set(record2.laneId,laneRecords);let sessionId=record2.subagentSessionId?.trim();if(sessionId)recordCountBySubagentSessionId.set(sessionId,(recordCountBySubagentSessionId.get(sessionId)??0)+1)}return args2.expectedLanes.map((expectedLane)=>{let expectedWorkflowLane=expectedLane.workflowLane,expectedOwnedLanes=expectedLane.ownedWorkflowLanes?.length?expectedLane.ownedWorkflowLanes:[expectedWorkflowLane],failed=(failure)=>({ok:!1,expectedLane,expectedWorkflowLane,expectedOwnedLanes,failure});if(batchFailure&&!batchFailure.ok)return failed(batchFailure.failure);let laneRecords=recordsByLaneId.get(expectedLane.laneId)??[];if(laneRecords.length===0)return failed(failedLaneValidation("record.missing","exactly one record",0).failure);if(laneRecords.length!==1)return failed(failedLaneValidation("record.duplicate_lane","exactly one record",laneRecords.length).failure);let record2=laneRecords[0],subagentSessionId=record2.subagentSessionId?.trim();if(!subagentSessionId)return failed(failedLaneValidation("record.subagent_session_id","non-empty child session id",record2.subagentSessionId??"(missing)").failure);if(recordCountBySubagentSessionId.get(subagentSessionId)!==1)return failed(failedLaneValidation("record.duplicate_subagent_session_id","one record per child session",recordCountBySubagentSessionId.get(subagentSessionId)).failure);if(args2.forbiddenSubagentSessionIds.has(subagentSessionId))return failed(failedLaneValidation("record.forbidden_subagent_session_id","child session not reused from a forbidden phase",subagentSessionId).failure);if(record2.createdAt<validatedAtMs)return failed(failedLaneValidation("record.created_at",`at or after ${args2.validatedAt}`,new Date(record2.createdAt).toISOString()).failure);let recordIntegrity=analyzeLaneRecordResultIntegrity({record:record2,result:record2.result,expected:{mode:args2.expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes:expectedOwnedLanes,prHeadSha:args2.expectedPrHeadSha??record2.workspace?.prHeadSha??"",gitHead:args2.expectedPrHeadSha??record2.workspace?.gitHead??"",checkWorkflowLane:args2.checkWorkflowLane},requireCompleted:!0,allowTranscriptIncompleteRecovery:args2.expectedMode==="swarm-pr-review:base"||args2.expectedMode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return failed(recordIntegrity.failure);return{ok:!0,record:record2,expectedLane,expectedWorkflowLane,expectedOwnedLanes}})}function recordsPassingBatchIntegrity3(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,diagnostics){let records=findByBatchId(directory,batchId,{parentSessionId:state.sessionID}),analyses=analyzePrReviewBatchRecordIntegrity({batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,records,expectedPrHeadSha:state.prHeadSha});for(let analysis of analyses)if(!analysis.ok&&diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${analysis.expectedLane.laneId} workflow_lane=${analysis.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(analysis.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return analyses.filter((analysis)=>analysis.ok)}function successfulObligationsFromExactBatch2(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane=!0,forbiddenSubagentSessionIds=new Set,expectedRevisionDigest,diagnostics,reviewerClaims){let successful2=new Set;for(let qualified of recordsPassingBatchIntegrity3(directory,state,batchId,expectedLanes,expectedMode,validatedAt,checkWorkflowLane,forbiddenSubagentSessionIds,diagnostics)){let structuredCoverage=validateExactStructuredReceiptCoverage2({record:qualified.record,result:qualified.record.result,artifact:null,expected:{mode:expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"?expectedMode:"swarm-pr-review:base",workflowLane:qualified.expectedWorkflowLane,ownedWorkflowLanes:qualified.expectedOwnedLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state.workflowInstanceId,workflowRevision:qualified.record.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope:state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0}});if(structuredCoverage.status==="accepted"){for(let obligation of structuredCoverage.creditedWorkflowLanes)successful2.add(obligation);continue}if(structuredCoverage.status==="rejected"){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${batchId} lane=${qualified.expectedLane.laneId} workflow_lane=${qualified.expectedWorkflowLane}: ${formatPrReviewLaneValidationFailure(structuredCoverage.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));continue}if(workflowArtifactHasContractMarker(directory,state,qualified.record,expectedMode,qualified.expectedWorkflowLane,qualified.expectedLane.reviewItemIds,expectedRevisionDigest,qualified.expectedOwnedLanes,diagnostics,reviewerClaims))for(let obligation of qualified.expectedOwnedLanes)successful2.add(obligation)}return successful2}function ownedLaneSetsEqual(recordOwned,expectedOwned){if(!recordOwned||recordOwned.length===0)return expectedOwned.length===1;let recordSet=new Set(recordOwned),expectedSet=new Set(expectedOwned);if(recordSet.size!==recordOwned.length||recordSet.size!==expectedSet.size)return!1;return recordOwned.every((owned)=>expectedSet.has(owned))}function validateExactStructuredReceiptCoverage2(input){if(input.expected.mode!=="swarm-pr-review:base"&&input.expected.mode!=="swarm-pr-review:micro")return{status:"absent"};let rawReceipt=input.result.prReviewResultReceipt;if(!rawReceipt)return{status:"absent"};let parsedReceipt2=PrReviewResultReceiptSchema.safeParse(rawReceipt);if(!parsedReceipt2.success)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","schema-valid exact child/workflow/revision-bound structured receipt","invalid structured receipt").failure};if(input.expected.workflowInstanceId===void 0||input.expected.workflowRevision===void 0||input.expected.baseSha===void 0)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","live workflow instance/revision/base identity","missing live workflow instance/revision/base identity").failure};let receipt=parsedReceipt2.data,recordWorkflowInstanceId=decodePrReviewWorkflowBinding(input.record.jobId),recordWorkflowRevision=input.record.workflowGeneration,ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane];if(!recordWorkflowInstanceId||recordWorkflowRevision===void 0||recordWorkflowInstanceId!==input.expected.workflowInstanceId||recordWorkflowRevision!==input.expected.workflowRevision||receipt.mode!==input.expected.mode||receipt.workflowInstanceId!==recordWorkflowInstanceId||receipt.workflowRevision!==recordWorkflowRevision||receipt.baseSha!==input.expected.baseSha||receipt.batchId!==input.record.batchId||receipt.laneId!==input.record.laneId||receipt.childSessionId!==input.record.subagentSessionId||receipt.workflowLane!==input.expected.workflowLane||!ownedLaneSetsEqual(receipt.ownedWorkflowLanes,ownedWorkflowLanes)||receipt.headSha!==input.expected.prHeadSha||receipt.dispatchRevisionDigest!==input.expected.revisionDigest)return{status:"rejected",failure:failedLaneValidation("discovery.coverage","exact child/workflow/revision-bound structured receipt","mismatched structured receipt").failure};return{status:"accepted",creditedWorkflowLanes:receipt.envelope.creditedLanes.filter((lane)=>ownedWorkflowLanes.includes(lane)),receipt}}function analyzeLaneArtifactIntegrity(args2){let{record:record2,result,artifact,expected}=args2;if(!artifact)return failedLaneValidation("artifact.readable","readable stored artifact","missing or invalid");if(artifact.ref!==result.outputRef?.trim())return failedLaneValidation("artifact.ref",result.outputRef?.trim()??"(missing)",artifact.ref);if(artifact.batchId!==record2.batchId)return failedLaneValidation("artifact.batch_id",record2.batchId??"(missing)",artifact.batchId);if(artifact.laneId!==record2.laneId)return failedLaneValidation("artifact.lane_id",record2.laneId??"(missing)",artifact.laneId);if(artifact.mode!==expected.mode)return failedLaneValidation("artifact.mode",expected.mode,artifact.mode??"(missing)");if(artifact.sessionId!==record2.subagentSessionId)return failedLaneValidation("artifact.session_id",record2.subagentSessionId,artifact.sessionId??"(missing)");if(artifact.parentSessionId!==record2.parentSessionId)return failedLaneValidation("artifact.parent_session_id",record2.parentSessionId,artifact.parentSessionId??"(missing)");if(artifact.agent!==record2.swarmPrefixedAgent)return failedLaneValidation("artifact.agent",record2.swarmPrefixedAgent,artifact.agent);if(artifact.role!==record2.normalizedAgent)return failedLaneValidation("artifact.role",record2.normalizedAgent,artifact.role);if(artifact.source!=="collect_lane_results")return failedLaneValidation("artifact.source","collect_lane_results",artifact.source);if(artifact.workflowLane!==record2.workflowLane)return failedLaneValidation("artifact.workflow_lane_record",record2.workflowLane??"(missing)",artifact.workflowLane??"(missing)");if(artifact.workflowLane!==expected.workflowLane)return failedLaneValidation("artifact.workflow_lane_expected",expected.workflowLane,artifact.workflowLane??"(missing)");if(artifact.prHeadSha!==expected.prHeadSha)return failedLaneValidation("artifact.pr_head_sha",expected.prHeadSha,artifact.prHeadSha??"(missing)");if(artifact.gitHead!==expected.gitHead)return failedLaneValidation("artifact.git_head",expected.gitHead,artifact.gitHead??"(missing)");if(artifact.revisionDigest!==expected.revisionDigest)return failedLaneValidation("artifact.revision_digest",expected.revisionDigest,artifact.revisionDigest??"(missing)");if(expected.reviewScope!==void 0&&record2.workspace?.scope!==expected.reviewScope)return failedLaneValidation("record.scope",expected.reviewScope,record2.workspace?.scope??"(missing)");if(expected.reviewScope!==void 0&&artifact.scope!==expected.reviewScope)return failedLaneValidation("artifact.scope",expected.reviewScope,artifact.scope??"(missing)");if(artifact.digest!==result.digest)return failedLaneValidation("artifact.digest",result.digest,artifact.digest);if(artifact.chars!==result.chars)return failedLaneValidation("artifact.chars",result.chars,artifact.chars);return{ok:!0}}function loadArtifactPassingLaneIntegrity2(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics){let ref=record2.result?.outputRef?.trim();if(!ref)return null;let artifact=readLaneOutput(directory,ref)?.artifact??null,expectedReviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,integrity=analyzeLaneArtifactIntegrity({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,prHeadSha:record2.workspace?.prHeadSha??"",gitHead:record2.workspace?.gitHead??"",revisionDigest:expectedRevisionDigest,reviewScope:expectedReviewScope}});if(!integrity.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(integrity.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return null}return artifact}function workflowArtifactHasContractMarker(directory,state,record2,expectedMode,expectedWorkflowLane,reviewItemIds,expectedRevisionDigest,ownedWorkflowLanes,diagnostics,reviewerClaims){let ref=record2.result?.outputRef?.trim(),artifact=expectedRevisionDigest?loadArtifactPassingLaneIntegrity2(directory,state,record2,expectedMode,expectedWorkflowLane,expectedRevisionDigest,diagnostics):null;if(!artifact)return!1;if(expectedMode==="swarm-pr-review:reviewer"||expectedMode==="swarm-pr-review:critic"){let phase=expectedMode==="swarm-pr-review:reviewer"?"reviewer":"critic";return analyzeLegacyVerdictRowContract(artifact.text,reviewItemIds??[],phase,reviewerClaims).ok}if(expectedMode==="swarm-pr-feedback:verification")return/^\[FEEDBACK-VERIFIED\]\s*\|/m.test(artifact.text);let feedbackVerdict={"swarm-pr-feedback:stage-b-reviewer":["[STAGE-B-REVIEW]","APPROVE"],"swarm-pr-feedback:stage-b-test":["[STAGE-B-TEST]","PASS"],"swarm-pr-feedback:closeout-reviewer":["[CLOSEOUT-REVIEW]","APPROVE"],"swarm-pr-feedback:closeout-critic":["[CLOSEOUT-CRITIC]","APPROVE"]}[expectedMode];if(feedbackVerdict)return Boolean(reviewItemIds?.length&&reviewItemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifact.text,feedbackVerdict[0],itemId,feedbackVerdict[1])));if(expectedMode==="swarm-pr-review:base"||expectedMode==="swarm-pr-review:micro"){let reviewScope=state.mode==="PR_REVIEW"&&state.prReviewBaseSha&&state.prHeadSha?`complete PR diff ${state.prReviewBaseSha}...${state.prHeadSha}`:void 0,validation=validatePrReviewDiscoveryLaneCompletion2({record:record2,result:record2.result,artifact,expected:{mode:expectedMode,workflowLane:expectedWorkflowLane,ownedWorkflowLanes,prHeadSha:state.prHeadSha??"",gitHead:state.prHeadSha??"",revisionDigest:expectedRevisionDigest??"",workflowInstanceId:state.workflowInstanceId,workflowRevision:record2.workflowGeneration,baseSha:state.prReviewBaseSha,reviewScope}});if(!validation.ok){if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS)diagnostics.push(`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${expectedWorkflowLane} output_ref=${ref}: ${formatPrReviewLaneValidationFailure(validation.failure)}`.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2));return!1}return!0}let coveredLanes=ownedWorkflowLanes?.length?ownedWorkflowLanes:[expectedWorkflowLane],coverageAnalyses=coveredLanes.map((coveredLane)=>({coveredLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,coveredLane,coveredLanes,expectedMode)}));if(coverageAnalyses.some(({analysis})=>!analysis.covered)){for(let{coveredLane,analysis}of coverageAnalyses){if(analysis.covered||analysis.issues.length===0)continue;if(diagnostics&&diagnostics.length<MAX_BASE_COVERAGE_DIAGNOSTICS){let diagnostic=`batch=${record2.batchId??"(missing)"} lane=${record2.laneId??"(missing)"} workflow_lane=${coveredLane} output_ref=${ref} digest=${record2.result?.digest??"(missing)"}: ${analysis.issues.join("; ")}`;diagnostics.push(diagnostic.slice(0,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2))}}return!1}if(coveredLanes.length>1){let seenEvidence=new Map;for(let coveredLane of coveredLanes){let evidence2=extractLaneCoverageEvidenceText(artifact.text,coveredLane,coveredLanes,expectedMode);if(evidence2===null)continue;if(seenEvidence.get(evidence2))return!1;seenEvidence.set(evidence2,coveredLane)}}return!0}function analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode,acceptPartial=!1){let fallbackFamily=resolvePrReviewRowFamily(expectedWorkflowLane,mode),issues=[],normalized=normalizeCandidateArtifactCached(text,fallbackFamily),canonicalText=normalized.text,repairKinds=normalized.repairKinds,salvaged=repairKinds.length>0,cleanAttestationSalvaged=!1,header=selectCandidateHeader(canonicalText.split(/\r?\n/));if(header===null||!header.markerBearing||header.family!==fallbackFamily)return appendBoundedCandidateIssue(issues,`field header: expected one exact canonical ${fallbackFamily} [CANDIDATE] header before discovery rows`),{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:"discovery.header"};let parsed=parseCandidates({output_ref:"pr-workflow:discovery-artifact",batchId:"pr-workflow",laneId:expectedWorkflowLane,agent:"explorer",role:"explorer",digest:"0".repeat(64),text:canonicalText,artifact_status:"ok",source:"collect_lane_results",produced_at:"1970-01-01T00:00:00.000Z"},{accept_partial:acceptPartial,accept_degraded:!1,degraded:!1,row_format_version:1,producer:"swarm-pr-review",expected_family:fallbackFamily,...fallbackFamily==="base_explorer"?{expected_lane:expectedWorkflowLane,expected_lanes:[...ownedWorkflowLanes]}:{expected_micro_lane:expectedWorkflowLane,expected_micro_lanes:[...ownedWorkflowLanes]}});if(parsed.error)appendBoundedCandidateIssue(issues,parsed.error);if(parsed.clean_attestation_salvaged)cleanAttestationSalvaged=!0,salvaged=!0,appendBoundedCandidateIssue(issues,parsed.clean_attestation_salvage_reason??"CLEAN attestation discredited; candidate rows retained");for(let detail of parsed.diagnostics.parse_error_details)appendBoundedCandidateIssue(issues,`row ${detail.row_index+1} field ${detail.field}: ${detail.message}`);let hasParseFailure=Boolean(parsed.error)||Boolean(parsed.clean_attestation_salvaged)||parsed.diagnostics.parse_error_details.length>0,extractedCandidateIds=parseCanonicalCandidateRows(canonicalText,fallbackFamily).rows.map((row)=>row.candidateId);if(new Set(extractedCandidateIds).size!==extractedCandidateIds.length)return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:"discovery.row"};let matchingCandidate=parsed.candidates.find((candidate)=>(candidate.lane??candidate.micro_lane)===expectedWorkflowLane);if(matchingCandidate)return{covered:!0,evidence:[matchingCandidate.severity,matchingCandidate.category,matchingCandidate.file_line,matchingCandidate.claim,matchingCandidate.evidence_summary,matchingCandidate.impact_context??matchingCandidate.invariant_violated,matchingCandidate.confidence].join("\x00"),issues,coverageKind:"candidate",salvaged,repairKinds,cleanAttestationSalvaged};let clean=parsed.clean_attestation;if(clean&&(clean.row_format_family==="base_explorer"?clean.lane:clean.micro_lane)===expectedWorkflowLane)return{covered:!0,evidence:`${clean.coverage_scope}\x00${clean.evidence}`,issues,coverageKind:"clean",salvaged,repairKinds,cleanAttestationSalvaged};return{covered:!1,evidence:null,issues,coverageKind:null,salvaged,repairKinds,cleanAttestationSalvaged,failurePredicate:hasParseFailure?"discovery.row":"discovery.coverage"}}function validatePrReviewDiscoveryLaneCompletion2(input){let ownedWorkflowLanes=input.expected.ownedWorkflowLanes?.length?[...input.expected.ownedWorkflowLanes]:[input.expected.workflowLane],recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,ownedWorkflowLanes,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,checkWorkflowLane:input.expected.checkWorkflowLane??!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro"});if(!recordIntegrity.ok)return recordIntegrity;let structuredCoverage=validateExactStructuredReceiptCoverage2(input);if(structuredCoverage.status==="accepted")return{ok:!0};if(structuredCoverage.status==="rejected")return{ok:!1,failure:structuredCoverage.failure};if((input.expected.mode==="swarm-pr-review:base"||input.expected.mode==="swarm-pr-review:micro")&&!prReviewLegacyTranscriptCompatibilityEnabled(input.record.prReviewLegacyTranscriptCompatibility))return failedLaneValidation("discovery.coverage","child-bound structured receipt","missing structured receipt (legacy transcript adapter disabled)");let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode:input.expected.mode,workflowLane:input.expected.workflowLane,prHeadSha:input.expected.prHeadSha,gitHead:input.expected.gitHead,revisionDigest:input.expected.revisionDigest,reviewScope:input.expected.reviewScope}});if(!artifactIntegrity.ok)return artifactIntegrity;let artifact=input.artifact,analyses=ownedWorkflowLanes.map((workflowLane)=>({workflowLane,analysis:analyzePrReviewDiscoveryArtifact(artifact.text,workflowLane,ownedWorkflowLanes,input.expected.mode,input.result.transcriptIncomplete===!0)})),salvagedLanes=[],recoveries=[],previewTruncated=input.result.truncated===!0,transcriptIncomplete=input.result.transcriptIncomplete===!0;for(let{workflowLane,analysis}of analyses){if(!analysis.covered)continue;let laneRecoveries=[];if(previewTruncated)laneRecoveries.push({workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"});if(transcriptIncomplete){if(analysis.coverageKind==="candidate")laneRecoveries.push({workflowLane,kind:"transcript-incomplete-terminal-candidate",reason:"partial transcript accepted only because a durable [CANDIDATE] row proved this lane"});else if(analysis.coverageKind==="clean")return failedLaneValidation("result.transcript_incomplete","complete transcript for every [CLEAN] attestation",`workflow lane ${workflowLane} was covered only by [CLEAN] after a partial transcript fetch`)}if(laneRecoveries.length===0&&!analysis.salvaged&&analysis.issues.length===0)continue;if(salvagedLanes.push(workflowLane),analysis.repairKinds.length>0)laneRecoveries.push({workflowLane,kind:"parser-normalization",reason:`structural repairs applied: ${analysis.repairKinds.join(", ")}`});if(analysis.cleanAttestationSalvaged)laneRecoveries.push({workflowLane,kind:"clean-attestation-salvaged",reason:"a conflicting [CLEAN] attestation was discredited while the independently validated candidate rows were retained"});if(analysis.issues.length>0)laneRecoveries.push({workflowLane,kind:"parser-row-recovery",reason:"one or more malformed or out-of-ownership rows were dropped while retaining valid coverage"});recoveries.push(...laneRecoveries);let reason=laneRecoveries.map((recovery)=>recovery.reason).join("; ");warn(`[pr-workflow-gate] discovery artifact salvaged: batch=${input.record.batchId??"(missing)"} lane=${input.record.laneId??"(missing)"} workflow_lane=${workflowLane} — ${reason}; retained coverage from the valid rows. Dropped-row diagnostics: ${analysis.issues.join("; ")||"(none)"}`)}let failedCoverage=analyses.find(({analysis})=>!analysis.covered);if(failedCoverage)return failedLaneValidation(failedCoverage.analysis.failurePredicate??"discovery.coverage",`one valid ${input.expected.mode==="swarm-pr-review:base"?"base_explorer":"micro_lane"} [CANDIDATE] row or [CLEAN] attestation for ${failedCoverage.workflowLane}`,failedCoverage.analysis.issues.join("; ")||"no matching lane row");if(ownedWorkflowLanes.length>1){let seenEvidence=new Map;for(let{workflowLane,analysis}of analyses){if(analysis.evidence===null)continue;let priorLane=seenEvidence.get(analysis.evidence);if(priorLane)return failedLaneValidation("discovery.duplicate_evidence","distinct evidence for every owned workflow lane",`${priorLane} and ${workflowLane} share evidence`);seenEvidence.set(analysis.evidence,workflowLane)}}return salvagedLanes.length>0?{ok:!0,salvaged:salvagedLanes,recoveries}:{ok:!0}}async function validatePrWorkflowTransportRecovery(input){let mode=input.record.mode?.trim();if(!(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic")&&input.result.truncated!==!0&&input.result.transcriptIncomplete!==!0)return{ok:!0};let workflowLane=input.record.workflowLane?.trim();if(!mode||!workflowLane)return{ok:!1,reason:"structured workflow transport recovery requires non-empty mode and workflow_lane provenance"};let state=await requireAnyActiveState(input.directory,input.record.parentSessionId),batchId=input.record.batchId?.trim(),laneId=input.record.laneId?.trim(),verdictPhase=mode==="swarm-pr-review:reviewer"?"reviewer":mode==="swarm-pr-review:critic"?"critic":null,declaredItemIds=(verdictPhase?(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===verdictPhase)?.lanes.find((candidate)=>candidate.laneId===laneId):void 0)?.reviewItemIds??[],rejectedReceipt=declaredItemIds.length>0?{assignedReviewItemIds:[...declaredItemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...declaredItemIds]}:void 0,recordIntegrity=analyzeLaneRecordResultIntegrity({record:input.record,result:input.result,expected:{mode,workflowLane,ownedWorkflowLanes:[workflowLane],prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",checkWorkflowLane:!0},requireCompleted:!1,allowTranscriptIncompleteRecovery:!1});if(!recordIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(recordIntegrity.failure),failure:recordIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactIntegrity=analyzeLaneArtifactIntegrity({record:input.record,result:input.result,artifact:input.artifact,expected:{mode,workflowLane,prHeadSha:input.record.workspace?.prHeadSha??"",gitHead:input.record.workspace?.gitHead??"",revisionDigest:input.revisionDigest,reviewScope:input.record.workspace?.scope??void 0}});if(!artifactIntegrity.ok)return{ok:!1,reason:formatPrReviewLaneValidationFailure(artifactIntegrity.failure),failure:artifactIntegrity.failure,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let expectedMode=mode.startsWith("swarm-pr-review:")?"PR_REVIEW":mode.startsWith("swarm-pr-feedback:")?"PR_FEEDBACK":null;if(!expectedMode)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(state.mode!==expectedMode)return{ok:!1,reason:`active workflow mode mismatch; expected ${expectedMode}, got ${state.mode}`,...rejectedReceipt?{receipt:rejectedReceipt}:{}};let artifactText=input.artifact?.text??"",prReviewGateContext=state.mode==="PR_REVIEW"?{revisionDigest:input.revisionDigest}:void 0;if(!batchId||!laneId)return{ok:!1,reason:"structured workflow transport recovery requires non-empty batch_id and lane_id provenance",...rejectedReceipt?{receipt:rejectedReceipt}:{}};if(mode==="swarm-pr-review:reviewer"||mode==="swarm-pr-review:critic"){let phase=verdictPhase??"reviewer",lane=(state.prReviewValidationBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===phase)?.lanes.find((candidate)=>candidate.laneId===laneId);if(!lane||lane.workflowLane!==workflowLane)return{ok:!1,reason:"no matching declared reviewer/critic lane ownership was found for this transport recovery",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let itemIds=lane.reviewItemIds??[],reviewerClaims=phase==="critic"?authoritativeReviewerClaims2(input.directory,state,prReviewGateContext??{revisionDigest:input.revisionDigest}):void 0;if(phase==="critic"&&(!reviewerClaims||reviewerClaims.size===0))return{ok:!1,reason:"critic transport recovery requires authoritative settled reviewer claims for every assigned item",...rejectedReceipt?{receipt:rejectedReceipt}:{}};let analysis=analyzeLegacyVerdictRowContract(artifactText,itemIds,phase,reviewerClaims);if(!analysis.ok){let failure=failedLaneValidation(phase==="reviewer"?"reviewer.verdict_rows":"critic.verdict_rows",analysis.expected,analysis.actual).failure;return{ok:!1,reason:formatPrReviewLaneValidationFailure(failure),failure,receipt:{assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[],rejectedReviewItemIds:[...itemIds]}}}let receipt={assignedReviewItemIds:[...itemIds],acceptedReviewItemIds:[...itemIds],rejectedReviewItemIds:[]},recoveries=[...(analysis.recoveries??[]).map(({recovery,itemId})=>({workflowLane,kind:"legacy-verdict-row-recovery",reason:recovery==="legacy-fidelity-safe"?`legacy verdict row ${itemId} used trailing-field pipe recovery with full field fidelity`:`legacy verdict row ${itemId} used trailing-field pipe recovery with lossy prose normalization`})),...input.result.truncated===!0?[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]:[]];return recoveries.length>0?{ok:!0,receipt,recoveries}:{ok:!0,receipt}}else if(mode==="swarm-pr-feedback:verification"){let lane=(state.prFeedbackVerifications??[]).find((candidate)=>candidate.batchId===batchId)?.ownership.find((candidate)=>candidate.laneId===laneId);if(!lane||workflowLane!==lane.laneId)return{ok:!1,reason:"no matching declared PR_FEEDBACK verification ownership was found for this transport recovery"};let itemIds=lane?.ownedItemIds??[];if(itemIds.length===0||!legacyFeedbackArtifactTextCoversItems(artifactText,itemIds))return{ok:!1,reason:"every assigned PR_FEEDBACK verification item requires one exact [FEEDBACK-VERIFIED] row in the durable artifact"}}else{let feedbackPhase={"swarm-pr-feedback:stage-b-reviewer":{phase:"stage-b-reviewer",marker:"[STAGE-B-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:stage-b-test":{phase:"stage-b-test",marker:"[STAGE-B-TEST]",verdict:"PASS"},"swarm-pr-feedback:closeout-reviewer":{phase:"closeout-reviewer",marker:"[CLOSEOUT-REVIEW]",verdict:"APPROVE"},"swarm-pr-feedback:closeout-critic":{phase:"closeout-critic",marker:"[CLOSEOUT-CRITIC]",verdict:"APPROVE"}}[mode];if(!feedbackPhase)return{ok:!1,reason:`structured workflow transport recovery does not support mode "${mode}"`};let batch=(state.prFeedbackGateBatches??[]).find((candidate)=>candidate.batchId===batchId&&candidate.phase===feedbackPhase.phase&&candidate.laneId===laneId);if(!batch||workflowLane!==feedbackPhase.phase)return{ok:!1,reason:"no matching declared ordered PR_FEEDBACK lane provenance was found for this transport recovery"};let itemIds=batch?.itemIds??[];if(itemIds.length===0||!itemIds.every((itemId)=>legacyArtifactHasExactPositiveVerdictRow(artifactText,feedbackPhase.marker,itemId,feedbackPhase.verdict)))return{ok:!1,reason:"every assigned ordered PR_FEEDBACK item requires one exact positive verdict row in the durable artifact"}}return input.result.truncated===!0?{ok:!0,recoveries:[{workflowLane,kind:"truncated-preview-durable-artifact",reason:"inline preview truncated; durable artifact retained exact coverage"}]}:{ok:!0}}function prReviewDiscoveryArtifactCoversLane(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).covered}function extractLaneCoverageEvidenceText(text,expectedWorkflowLane,ownedWorkflowLanes=[expectedWorkflowLane],mode){return analyzePrReviewDiscoveryArtifact(text,expectedWorkflowLane,ownedWorkflowLanes,mode).evidence}async function persistState2(directory,state){let validated=PrWorkflowGateStateSchema.parse(state);await withSessionStateMutation(directory,validated.sessionID,async()=>{let nextState=await writeStateWhileLocked(directory,validated);Object.assign(state,nextState)})}function boundSalvagedSchemaError(message){return message.length<=MAX_SALVAGED_SCHEMA_ERROR_CHARS?message:`${message.slice(0,MAX_SALVAGED_SCHEMA_ERROR_CHARS-1)}…`}async function readPrWorkflowGateStateForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),filePath=workflowGateStatePath(directory,normalizedSessionID),raw;try{raw=await fsp7.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let parsedJson;try{parsedJson=JSON.parse(raw)}catch{throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is not valid JSON`)}let parsed=PrWorkflowGateStateSchema.safeParse(parsedJson);if(parsed.success)return{state:parsed.data,salvaged:!1,schemaErrors:[],revisionSalvageable:!0,armedShapeUnreadable:!1};let invalidError=Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid`);if(typeof parsedJson!=="object"||parsedJson===null||Array.isArray(parsedJson))throw invalidError;let rawRecord=parsedJson,salvagedSessionID=exports_external.string().min(1).safeParse(rawRecord.sessionID),salvagedMode=exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]).safeParse(rawRecord.mode);if(!salvagedSessionID.success||!salvagedMode.success)throw invalidError;let salvagedRevision=exports_external.number().int().nonnegative().safeParse(rawRecord.revision),salvagedHead=exports_external.string().min(1).safeParse(rawRecord.prHeadSha),salvagedActivatedAt=exports_external.string().min(1).safeParse(rawRecord.activatedAt),salvagedUpdatedAt=exports_external.string().min(1).safeParse(rawRecord.updatedAt),armedKeyPresent=rawRecord.prFeedbackReadyToPublish!==void 0,salvagedArmed=PrFeedbackReadyToPublishRecordSchema.safeParse(rawRecord.prFeedbackReadyToPublish),publicationKeyPresent=rawRecord.prFeedbackPublication!==void 0,salvagedPublication=PrFeedbackPublicationStateSchema.safeParse(rawRecord.prFeedbackPublication),publicationShapeUnreadable=publicationKeyPresent&&!salvagedPublication.success,salvagedCheckoutRecovery=PrWorkflowCheckoutRecoveryRecordSchema.safeParse(rawRecord.checkoutRecovery),armedShapeUnreadable=armedKeyPresent&&!salvagedArmed.success||publicationShapeUnreadable,schemaErrors=parsed.error.issues.slice(0,MAX_SALVAGED_SCHEMA_ERRORS).map((issue2)=>boundSalvagedSchemaError(`${issue2.path.join(".")||"(root)"}: ${issue2.message}`)),disclosure=`DEGRADED: PR workflow gate state for session "${normalizedSessionID}" failed schema validation and was SALVAGED for recovery only (abort/status; write and completion paths still refuse it). Schema errors: ${schemaErrors.join("; ")}.`+(salvagedRevision.success?"":" state revision unsalvageable.")+(armedShapeUnreadable?" prFeedbackReadyToPublish is present but unreadable; treated as ARMED (fail-closed).":"")+(publicationShapeUnreadable?" prFeedbackPublication is present but unreadable; treated as ARMED (fail-closed).":"");return{state:{schemaVersion:GATE_SCHEMA_VERSION,revision:salvagedRevision.success?salvagedRevision.data:0,sessionID:salvagedSessionID.data,mode:salvagedMode.data,activatedAt:salvagedActivatedAt.success?salvagedActivatedAt.data:isoNow(),updatedAt:salvagedUpdatedAt.success?salvagedUpdatedAt.data:isoNow(),...salvagedHead.success?{prHeadSha:salvagedHead.data}:{},...salvagedArmed.success?{prFeedbackReadyToPublish:salvagedArmed.data}:{},...salvagedPublication.success?{prFeedbackPublication:salvagedPublication.data}:{},...salvagedCheckoutRecovery.success?{checkoutRecovery:salvagedCheckoutRecovery.data}:{}},salvaged:!0,schemaErrors,disclosure,revisionSalvageable:salvagedRevision.success,armedShapeUnreadable}}var PR_REVIEW_REQUIRED_MICRO_LANE_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS,PR_REVIEW_BASE_LANE_FLOORS,PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR,PR_REVIEW_MICRO_LANE_FLOORS,MAX_PUBLICATION_HISTORY_GENERATIONS=4,MAX_PUBLICATION_ATTEMPTS=8,MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS=500,PUBLICATION_SCHEMA_VERSION=1,PUBLICATION_URL_CREDENTIALS_PATTERN,GATE_SCHEMA_VERSION=1,MAX_WORKFLOW_BATCHES=128,MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS=1024,MAX_RETIRED_CONSOLIDATED_LANES=64,MAX_RETIRED_FEEDBACK_ITEM_OWNERS=4096,MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS=128,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES,MAX_CANDIDATE_ISSUES_PER_ARTIFACT=8,MAX_BASE_COVERAGE_DIAGNOSTICS=8,MAX_BASE_COVERAGE_DIAGNOSTIC_CHARS2=1000,MAX_LANE_VALIDATION_VALUE_CHARS=240,DISPATCH_TOOL_NAME="dispatch_lanes_async",BLOCKING_DISPATCH_TOOL_NAME="dispatch_lanes",PrReviewBaseDimensionIdSchema,PrReviewBaseDispatchRecordSchema,PrReviewResiliencePolicyRecordSchema,PrReviewResilienceAttemptRecordSchema,PrReviewResilienceStateRecordSchema,PrFeedbackLaneOwnershipSchema,PrFeedbackVerificationRecordSchema,PrFeedbackStageACheckReceiptSchema,PrFeedbackStageARecordSchema,PrFeedbackGateBatchRecordSchema,PrFeedbackReadyToPublishRecordSchema,PrFeedbackPublicationEvidenceJoinSchema,PrFeedbackPublicationGenerationSchema,PrFeedbackPushAttemptSchema,PrFeedbackPublicationStateSchema,PrFeedbackInventoryAmendmentRecordSchema,PrReviewValidationBatchRecordSchema,PrReviewBatchCoherenceRecordSchema,PrFeedbackScopeDeclarationRecordSchema,PrWorkflowCheckoutRecoveryRecordSchema,PrFeedbackReviewHandoffRecordSchema,PrWorkflowGateStateSchema,PR_WORKFLOW_STALE_LANE_TIMEOUT_MS,MAX_DISCLOSED_LANE_IDS=10,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES,CAS_ESCAPE_DISCLOSURE="state revision unsalvageable; cleared without compare-and-swap",PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS=5000,PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS=180000,LIVE_SESSION_STATUS_TYPES,defaultGetSessionOps=()=>swarmState.opencodeClient?.session??null,laneLivenessWatchdogSurface,PrReviewResilienceCircuitOpenError,PrReviewResilienceRetryExhaustedError,snapshotPrReviewResiliencePolicy,MALFORMED_CIRCUIT_DIAGNOSTIC_LIMIT=64,malformedCircuitDiagnosticsSeen,TERMINAL_FAILED_DELEGATION_STATUSES2,MAX_COVER_UNIVERSE_BITS=12,PR_FEEDBACK_PHASE_ORDER,PR_FEEDBACK_PHASE_ROLE,PUBLICATION_IDENTITY_COMPONENTS,PUBLICATION_EVENT_TYPES,PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN,PR_REVIEW_FEEDBACK_CONSENT_MAX_BYTES=65536,PR_REVIEW_RUN_RESERVATION_MAX_BYTES=16384,PrReviewFeedbackHandoffArtifactSchema,PrReviewRunReservationSchema,PrReviewFeedbackConsentSchema,MAX_PR_REVIEW_RESERVATION_SCAN_ENTRIES=1024,MAX_PR_REVIEW_RUN_ID_SUFFIX_ATTEMPTS=64,PrReviewFindingProjectionSchema,_test_exports2,PR_WORKFLOW_SHARED_CONTROLLER_TOOLS,PR_REVIEW_CONTROLLER_TOOLS,PR_FEEDBACK_CONTROLLER_TOOLS,PR_REVIEW_READ_ONLY_TOOL_NAMES,PR_WORKFLOW_CD_PREFIX_PATTERN,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN,PR_WORKFLOW_MAX_CD_PREFIX_STRIPS=3,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN,PR_REVIEW_CLEAN_SENTINEL_ID="CLEAN-REVIEW",MAX_UNCLAIMED_ITEMS_IN_MESSAGE=50,FEEDBACK_NO_CHANGE_CLASSIFICATIONS,MAX_SALVAGED_SCHEMA_ERRORS=10,MAX_SALVAGED_SCHEMA_ERROR_CHARS=240;var init_pr_workflow_gate=__esm(()=>{init_zod();init_candidate_contract();init_candidate_parser();init_lane_output_store();init_pending_delegations();init_pr_review_collection_receipt();init_pr_review_contract();init_pr_review_trigger_contract();init_workspace_snapshot();init_constants();init_schema();init_project_db();init_core_events();init_pr_workflow_state();init_redaction();init_authorization();init_circuit();init_completion();init_legacy_transcript_adapter();init_persistence();init_reducer();init_scope_binding();init_state2();init_tool_metadata();init_canonical_root();init_logger();init_timeout();init_lane_liveness_watchdog();init_normalize_tool_name();init_utils2();init_completion();init_persistence();PR_REVIEW_REQUIRED_MICRO_LANE_IDS=PR_REVIEW_REQUIRED_TRIGGER_IDS,PR_REVIEW_DEPTH_TIER_THRESHOLDS={smallMaxChangedLines:100,smallMaxChangedFiles:5,mediumMaxChangedLines:1500,mediumMaxChangedFiles:50},PR_REVIEW_BASE_LANE_FLOORS={S:1,M:3,L:PR_REVIEW_BASE_DIMENSION_IDS.length},PR_REVIEW_TIER_L_CONSOLIDATED_LANE_FLOOR=PR_REVIEW_BASE_LANE_FLOORS.M+1,PR_REVIEW_MICRO_LANE_FLOORS={S:1,M:6,L:PR_REVIEW_REQUIRED_MICRO_LANE_IDS.length};PUBLICATION_URL_CREDENTIALS_PATTERN=/\b([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^\s/@:]+:[^\s/@]+@/g,MAX_PR_REVIEW_BASE_LANES_PER_BATCH=PR_REVIEW_BASE_DIMENSION_IDS.length,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS=MAX_WORKFLOW_BATCHES*MAX_PR_REVIEW_BASE_LANES_PER_BATCH,MAX_PR_WORKFLOW_GATE_DIRECTORY_ENTRIES=MAX_TRACKED_SESSIONS2*2+1,PrReviewBaseDimensionIdSchema=exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewBaseDispatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:PrReviewBaseDimensionIdSchema,ownedWorkflowLanes:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional()}).strict()).min(1).max(MAX_PR_REVIEW_BASE_LANES_PER_BATCH),validatedAt:exports_external.string().min(1)}).strict(),PrReviewResiliencePolicyRecordSchema=exports_external.object({enabled:exports_external.boolean(),canaryProbeMs:exports_external.number().int().positive(),statusProbeTimeoutMs:exports_external.number().int().positive(),correlatedFailureThreshold:exports_external.number().int().min(2).max(8),maxRetryAttemptsAfterInitial:exports_external.number().int().min(0).max(2),circuitOpenDurationMs:exports_external.number().int().min(1000).max(1800000).optional()}).strict(),PrReviewResilienceAttemptRecordSchema=exports_external.object({attempt:exports_external.union([exports_external.literal(0),exports_external.literal(1),exports_external.literal(2)]),targetDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).min(1).max(PR_REVIEW_BASE_DIMENSION_IDS.length),canaryBatchId:exports_external.string().min(1),canaryLaneId:exports_external.string().min(1),canaryWorkflowLane:PrReviewBaseDimensionIdSchema,admittedAt:exports_external.string().min(1),fanoutBatchId:exports_external.string().min(1).optional()}).strict(),PrReviewResilienceStateRecordSchema=exports_external.object({policy:PrReviewResiliencePolicyRecordSchema,attempts:exports_external.array(PrReviewResilienceAttemptRecordSchema).max(3),circuit:PrReviewCircuitRecordSchema.optional()}).strict(),PrFeedbackLaneOwnershipSchema=exports_external.object({laneId:exports_external.string().min(1),ownedItemIds:exports_external.array(exports_external.string().min(1)).min(1)}).strict(),PrFeedbackVerificationRecordSchema=exports_external.object({batchId:exports_external.string().min(1),ownership:exports_external.array(PrFeedbackLaneOwnershipSchema).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackStageACheckReceiptSchema=exports_external.object({category:exports_external.enum(["build","typecheck","lint","diff-check","reproduction"]),workingDirectory:exports_external.string().min(1).optional(),obligationId:exports_external.string().min(1).optional(),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional(),command:exports_external.array(exports_external.string().min(1)).min(1),targets:exports_external.array(exports_external.string().min(1)).min(1).optional(),feedbackTargets:exports_external.array(exports_external.object({feedbackItemId:exports_external.string().min(1),target:exports_external.string().min(1),expectedBehavior:exports_external.string().min(8),proofKind:exports_external.enum(["defect","metadata","source-proof","conflict","ci","user-decision"]).optional()}).strict()).min(1).optional(),durationMs:exports_external.number().nonnegative()}).strict(),PrFeedbackStageARecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),checks:exports_external.array(PrFeedbackStageACheckReceiptSchema).min(2).max(258),feedbackItemIds:exports_external.array(exports_external.string().min(1)).min(1).optional(),applicableCategories:exports_external.array(exports_external.enum(["build","typecheck","lint"])).max(3).optional(),applicableObligations:exports_external.array(exports_external.object({id:exports_external.string().min(1),category:exports_external.enum(["build","typecheck","lint"]),workingDirectory:exports_external.string().min(1),source:exports_external.string().min(1),validatorContract:exports_external.object({path:exports_external.string().min(1),id:exports_external.string().min(1)}).strict().optional()}).strict()).max(256).optional(),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackGateBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),laneId:exports_external.string().min(1),itemIds:exports_external.array(exports_external.string().min(1)).min(1),revisionDigest:exports_external.string().min(1),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackReadyToPublishRecordSchema=exports_external.object({revisionDigest:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),validatedAt:exports_external.string().min(1)}).strict(),PrFeedbackPublicationEvidenceJoinSchema=exports_external.object({stageAValidatedAt:exports_external.string().min(1),batches:exports_external.array(exports_external.object({phase:exports_external.enum(["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"]),batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict())}).strict(),PrFeedbackPublicationGenerationSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),generation:exports_external.number().int().positive(),state:exports_external.enum(["reviewing","armed","invalidated","push_in_flight","published","cancelled_without_publication"]),workspaceIdentity:exports_external.string().min(1),sessionID:exports_external.string().min(1),prTargetUrl:exports_external.string().min(1).optional(),intakeHeadSha:exports_external.string().min(1),localHeadRef:exports_external.string().min(1),localHead:exports_external.string().min(1),remoteName:exports_external.string().min(1),remoteUrlIdentity:exports_external.string().min(1).optional(),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),remoteRef:exports_external.string().startsWith("refs/remotes/"),revisionDigest:exports_external.string().min(1),evidence:PrFeedbackPublicationEvidenceJoinSchema,invalidationReason:exports_external.string().min(1).optional(),supersededByGeneration:exports_external.number().int().positive().optional(),createdAt:exports_external.string().min(1),armedAt:exports_external.string().min(1).optional(),invalidatedAt:exports_external.string().min(1).optional(),publishedAt:exports_external.string().min(1).optional(),cancelledAt:exports_external.string().min(1).optional()}).strict(),PrFeedbackPushAttemptSchema=exports_external.object({attemptId:exports_external.string().min(1),generation:exports_external.number().int().positive(),sessionID:exports_external.string().min(1),callID:exports_external.string().min(1).optional(),intentDigest:exports_external.string().regex(/^[0-9a-f]{64}$/),intent:exports_external.object({remote:exports_external.string().min(1),sourceSha:exports_external.string().min(1),destRef:exports_external.string().startsWith("refs/heads/")}).strict(),prePush:exports_external.object({localHead:exports_external.string().min(1),worktreeClean:exports_external.boolean(),remoteName:exports_external.string().min(1),remoteBranchRef:exports_external.string().startsWith("refs/heads/"),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),startedAt:exports_external.string().min(1),result:exports_external.object({outcome:exports_external.enum(["completed","rejected","uncertain","cancelled"]),exitStatus:exports_external.union([exports_external.number().int(),exports_external.literal("not-observed")]),diagnostic:exports_external.string().max(MAX_PUSH_ATTEMPT_DIAGNOSTIC_CHARS),postPush:exports_external.object({localHead:exports_external.string().min(1).nullable(),observedRemoteHead:exports_external.string().min(1).nullable()}).strict(),completedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrFeedbackPublicationStateSchema=exports_external.object({schemaVersion:exports_external.literal(PUBLICATION_SCHEMA_VERSION),active:PrFeedbackPublicationGenerationSchema.optional(),history:exports_external.array(PrFeedbackPublicationGenerationSchema).max(MAX_PUBLICATION_HISTORY_GENERATIONS),attempts:exports_external.array(PrFeedbackPushAttemptSchema).max(MAX_PUBLICATION_ATTEMPTS)}).strict(),PrFeedbackInventoryAmendmentRecordSchema=exports_external.object({entry:exports_external.string().min(1),amendedAt:exports_external.string().min(1),batch:exports_external.number().int().positive()}).strict(),PrReviewValidationBatchRecordSchema=exports_external.object({batchId:exports_external.string().min(1),phase:exports_external.enum(["council","reviewer","critic"]),lanes:exports_external.array(exports_external.object({laneId:exports_external.string().min(1),workflowLane:exports_external.string().min(1),reviewItemIds:exports_external.array(exports_external.string().min(1)).min(1).max(MAX_PR_REVIEW_COLLECTION_RECEIPT_ITEM_IDS).optional()}).strict()).min(1),validatedAt:exports_external.string().min(1)}).strict(),PrReviewBatchCoherenceRecordSchema=exports_external.object({validatedInventory:exports_external.array(exports_external.string().min(1)),reviewerItemBindings:exports_external.record(exports_external.string().min(1),exports_external.string().regex(/^[0-9a-f]{64}$/)).optional(),reviewerItemBindingKeyEncoding:exports_external.literal("prefixed-v1").optional()}).passthrough(),PrFeedbackScopeDeclarationRecordSchema=exports_external.object({taskId:exports_external.string().regex(/^\d+\.\d+(?:\.\d+)*$/),files:exports_external.array(exports_external.string().min(1)).min(1).max(1e4),revisionDigest:exports_external.string().min(1),declaredAt:exports_external.string().min(1),consumedByCallId:exports_external.string().min(1).optional()}).strict(),PrWorkflowCheckoutRecoveryRecordSchema=exports_external.object({code:exports_external.enum(["UNMERGED_INDEX","GIT_OPERATION_IN_PROGRESS","DIRTY_SUBMODULE","SWARM_STATE_TRACKING_ERROR","GIT_STATE_INDETERMINATE"]),retryable:exports_external.literal(!1),requiredAction:exports_external.string().min(1).max(2000),evidence:exports_external.object({worktreeRoot:exports_external.string().nullable(),gitDir:exports_external.string().nullable(),operations:exports_external.array(exports_external.string().min(1)).max(16),unmergedCodes:exports_external.array(exports_external.string().min(1)).max(16),paths:exports_external.array(exports_external.string()).max(20),trackedCount:exports_external.number().int().nonnegative(),untrackedCount:exports_external.number().int().nonnegative(),pathsTruncated:exports_external.boolean(),detail:exports_external.string().max(1000).optional()}).strict(),detectedAt:exports_external.string().min(1)}).strict(),PrFeedbackReviewHandoffRecordSchema=exports_external.object({path:exports_external.string().min(1).max(512),runId:exports_external.string().min(1).max(128),sourcePrHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),prUrl:exports_external.string().url().max(2000),findingIds:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),digest:exports_external.string().regex(/^[0-9a-f]{64}$/),sourceWorkflowInstanceId:exports_external.string().min(1).max(128),provenance:exports_external.enum(["active-review-v1","external-v1"])}).strict(),PrWorkflowGateStateSchema=exports_external.object({schemaVersion:exports_external.literal(GATE_SCHEMA_VERSION),revision:exports_external.number().int().nonnegative().default(0),workflowInstanceId:exports_external.string().min(1).max(128).optional(),sessionID:exports_external.string().min(1),mode:exports_external.enum(["PR_REVIEW","PR_FEEDBACK"]),activatedAt:exports_external.string().min(1),updatedAt:exports_external.string().min(1),prHeadSha:exports_external.string().min(1).optional(),prReviewBaseRef:exports_external.string().min(1).optional(),prReviewBaseSha:exports_external.string().min(1).optional(),prReviewDepthTier:exports_external.enum(["S","M","L"]).optional(),prReviewDiffStats:exports_external.object({changedLines:exports_external.number().int().nonnegative(),changedFiles:exports_external.number().int().nonnegative(),hasSubmoduleChange:exports_external.boolean().default(!1)}).strict().optional(),prReviewBaseDispatches:exports_external.array(PrReviewBaseDispatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBaseDispatch:PrReviewBaseDispatchRecordSchema.optional(),prReviewResilience:PrReviewResilienceStateRecordSchema.optional(),prReviewContractRetryDimensions:exports_external.array(PrReviewBaseDimensionIdSchema).max(PR_REVIEW_BASE_DIMENSION_IDS.length).optional(),prReviewTriggerLedger:exports_external.array(PrReviewInlineTriggerRowSchema).length(PR_REVIEW_REQUIRED_TRIGGER_IDS.length).optional(),prReviewTriggerEvalPath:exports_external.string().min(1).optional(),prReviewTriggerEvalRunId:exports_external.string().min(1).optional(),prReviewValidationBatches:exports_external.array(PrReviewValidationBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prReviewBatchCoherence:exports_external.record(exports_external.string().min(1),PrReviewBatchCoherenceRecordSchema).refine((entries)=>Object.keys(entries).length<=MAX_WORKFLOW_BATCHES,`prReviewBatchCoherence may not exceed ${MAX_WORKFLOW_BATCHES} entries`).optional(),prReviewRetiredReviewerSessionIds:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_REVIEWER_SESSION_IDS).optional(),prReviewRetiredConsolidatedLanes:exports_external.array(exports_external.string().min(1)).max(MAX_RETIRED_CONSOLIDATED_LANES).optional(),prReviewReservedRunId:exports_external.string().min(1).optional(),prReviewArtifactRunId:exports_external.string().min(1).optional(),prReviewFindingsPath:exports_external.string().min(1).optional(),prReviewPartialBaseCoverage:PrReviewPartialBaseCoverageRecordSchema.optional(),prReviewCoverageDisclosurePath:exports_external.string().min(1).max(512).optional(),prReviewCoverageDisclosureDigest:exports_external.string().regex(/^[0-9a-f]{64}$/).optional(),prReviewDimensionCancellations:exports_external.record(exports_external.enum(PR_REVIEW_BASE_DIMENSION_IDS),PrReviewDimensionCancellationRecordSchema).optional(),prReviewArtifactBoundaries:exports_external.array(exports_external.enum(["post_explorer","post_reviewer","post_critic"])).max(3).optional(),prReviewHandoffPath:exports_external.string().min(1).optional(),prReviewHandoffRequired:exports_external.boolean().optional(),checkoutRecovery:PrWorkflowCheckoutRecoveryRecordSchema.optional(),prFeedbackTargetUrl:exports_external.string().url().max(2000).optional(),prFeedbackReviewHandoff:PrFeedbackReviewHandoffRecordSchema.optional(),prFeedbackInventory:exports_external.array(exports_external.string().min(1)).min(1).optional(),prFeedbackInventoryAmendments:exports_external.array(PrFeedbackInventoryAmendmentRecordSchema).max(MAX_PR_FEEDBACK_INVENTORY_AMENDMENTS).optional(),prFeedbackVerifications:exports_external.array(PrFeedbackVerificationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackRetiredItemOwnership:exports_external.record(exports_external.string().min(1),exports_external.string().min(1)).refine((entries)=>Object.keys(entries).length<=MAX_RETIRED_FEEDBACK_ITEM_OWNERS,`prFeedbackRetiredItemOwnership may not exceed ${MAX_RETIRED_FEEDBACK_ITEM_OWNERS} entries`).optional(),prFeedbackVerification:PrFeedbackVerificationRecordSchema.optional(),prFeedbackStageA:PrFeedbackStageARecordSchema.optional(),prFeedbackGateBatches:exports_external.array(PrFeedbackGateBatchRecordSchema).max(MAX_WORKFLOW_BATCHES).optional(),prFeedbackReadyToPublish:PrFeedbackReadyToPublishRecordSchema.optional(),prFeedbackPublication:PrFeedbackPublicationStateSchema.optional(),prFeedbackArmedRecovery:exports_external.object({recoveredAt:exports_external.string().datetime(),prHeadSha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),revisionDigest:exports_external.string().min(1).max(256),generation:exports_external.number().int().nonnegative(),reason:exports_external.string().min(1).max(500)}).strict().optional(),prFeedbackRebindCount:exports_external.number().int().nonnegative().optional(),prFeedbackScopes:exports_external.array(PrFeedbackScopeDeclarationRecordSchema).max(MAX_WORKFLOW_BATCHES).optional()}).passthrough();PR_WORKFLOW_STALE_LANE_TIMEOUT_MS=DEFAULT_STALE_DELEGATION_TIMEOUT_MS,PR_WORKFLOW_SWEEPABLE_LANE_STATUSES=new Set(["pending","running"]),LIVE_SESSION_STATUS_TYPES=new Set(["busy","retry"]);laneLivenessWatchdogSurface={resolveEffectivePrLaneHorizonMs,classifyLaneLivenessCondition,evaluateLaneLivenessWatchdog:evaluateLaneLivenessWatchdogEscalation,readLaneActivity:defaultReadLaneActivity,hostStatusCalls:0,hostAbortCalls:0,evaluations:0};PrReviewResilienceCircuitOpenError=class PrReviewResilienceCircuitOpenError extends Error{code="PR_REVIEW_RESILIENCE_CIRCUIT_OPEN";constructor(message){super(message);this.name="PrReviewResilienceCircuitOpenError"}};PrReviewResilienceRetryExhaustedError=class PrReviewResilienceRetryExhaustedError extends Error{code="PR_REVIEW_RESILIENCE_RETRY_EXHAUSTED";constructor(message){super(message);this.name="PrReviewResilienceRetryExhaustedError"}};snapshotPrReviewResiliencePolicy=resolvePrReviewResiliencePolicy;malformedCircuitDiagnosticsSeen=new Set;TERMINAL_FAILED_DELEGATION_STATUSES2=CIRCUIT_TERMINAL_DELEGATION_STATUSES;PR_FEEDBACK_PHASE_ORDER=["stage-b-reviewer","stage-b-test","closeout-reviewer","closeout-critic"];PR_FEEDBACK_PHASE_ROLE={"stage-b-reviewer":"reviewer","stage-b-test":"test_engineer","closeout-reviewer":"reviewer","closeout-critic":"critic"};PUBLICATION_IDENTITY_COMPONENTS=["digest","head","worktree","upstream","remote-url","workspace-identity"];PUBLICATION_EVENT_TYPES=new Set(["pr_feedback_publication_armed","pr_feedback_publication_migrated","pr_feedback_push_attempt_started","pr_feedback_publication_invalidated","pr_feedback_published","pr_feedback_publication_cancelled"]);PR_REVIEW_HANDOFF_RELATIVE_PATH_PATTERN=/^pr-review\/([A-Za-z0-9][A-Za-z0-9._-]{0,127})\/feedback-handoff\.json$/,PrReviewFeedbackHandoffArtifactSchema=exports_external.object({schema_version:exports_external.literal(1),run_id:exports_external.string().min(1).max(128),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),created_at:exports_external.string().datetime(),pr_url:exports_external.string().url().max(2000),finding_ids:exports_external.array(exports_external.string().min(1).max(128)).min(1).max(1000),summary:exports_external.string().min(1).max(20000),provenance:exports_external.array(exports_external.string().min(1).max(4000)).min(1).max(1000)}).strict(),PrReviewRunReservationSchema=exports_external.object({schema_version:exports_external.literal(1),session_id:exports_external.string().min(1),workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),reserved_at:exports_external.string().datetime()}).strict(),PrReviewFeedbackConsentSchema=exports_external.object({schema_version:exports_external.literal(1),state:exports_external.enum(["offered","confirmed"]),session_id:exports_external.string().min(1),source_workflow_instance_id:exports_external.string().min(1),run_id:exports_external.string().min(1).max(128),handoff_path:exports_external.string().min(1).max(512),handoff_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),pr_url:exports_external.string().url().max(2000),pr_head_sha:exports_external.string().regex(/^[0-9a-f]{6,64}$/i),finding_ids_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),confirmation_command:exports_external.string().min(1).max(4000),offered_at:exports_external.string().datetime(),confirmed_at:exports_external.string().datetime().optional()}).strict();PrReviewFindingProjectionSchema=exports_external.object({finding_id:exports_external.string().min(1).max(128),status:exports_external.enum(["PENDING","CONFIRMED","DISPROVED","PRE_EXISTING"]),next_action:exports_external.enum(["route_to_reviewer","route_to_critic","report","suppress_with_reason","handoff_to_feedback"])}).passthrough();bindPrReviewReentryBindingReader(readPrReviewReentryBindingContext);_test_exports2={classifyPrReviewCircuitSignal,minimumConsolidatedLaneCover,analyzePrReviewBatchRecordIntegrity,MAX_COVER_UNIVERSE_BITS,extractCandidateIds,parseCanonicalCandidateRows,resolvePrReviewRowFamily,boundPublicationDiagnostic,workflowGateStateRelativePath,workflowGateStateLockRelativePath,workflowCheckoutMutationLockRelativePath,withPrWorkflowCheckoutMutationLock,resetTrackedStateCache:()=>{resetPrReviewPersistenceCaches(),malformedCircuitDiagnosticsSeen.clear(),_test_exports2.beforeTerminalClear=void 0,_test_exports2.beforeAbortClear=void 0,_test_exports2.beforePrFeedbackTransitionLock=void 0,_test_exports2.beforePrFeedbackTrackingSwitch=void 0,_test_exports2.afterPrFeedbackTrackingSwitch=void 0,_test_exports2.beforePrFeedbackTrackingPersist=void 0,_test_exports2.beforePrReviewReentryReservation=void 0,_test_exports2.beforeBoundedSwarmFileOpen=void 0,_test_exports2.beforeSessionStateLockWrite=void 0,_test_exports2.beforeCheckoutLockWrite=void 0,_test_exports2.beforeSafeDirectoryCreate=void 0,_test_exports2.beforeAtomicTempWrite=void 0,_test_exports2.beforeAtomicRename=void 0,_test_exports2.openCheckoutLock=defaultPersistenceHooks.openCheckoutLock,_test_exports2.removeCheckoutLock=defaultPersistenceHooks.removeCheckoutLock,_test_exports2.checkoutMutationActionTimeoutMs=CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,_test_exports2.classifyPrWorkflowGitStateAsync=classifyPrWorkflowGitState,_test_exports2.sweepStaleDelegationsAsync=sweepStaleDelegations,_test_exports2.probeLaneLivenessAsync=probeAlivePrWorkflowLaneSessions,_test_exports2.probeLaneSessionStatusTypesAsync=probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdogSurface.hostStatusCalls=0,laneLivenessWatchdogSurface.hostAbortCalls=0,laneLivenessWatchdogSurface.evaluations=0,laneLivenessWatchdogSurface.readLaneActivity=defaultReadLaneActivity,_test_exports2.getSessionOps=defaultGetSessionOps,_test_exports2.laneLivenessProbeTimeoutMs=PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,_test_exports2.pendingLaneLivenessThresholdMs=PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,closeAllProjectDbs()},beforeTerminalClear:void 0,beforeAbortClear:void 0,beforePrFeedbackTransitionLock:void 0,beforePrFeedbackTrackingSwitch:void 0,afterPrFeedbackTrackingSwitch:void 0,beforePrFeedbackTrackingPersist:void 0,beforePrReviewReentryReservation:void 0,beforeBoundedSwarmFileOpen:void 0,beforeSessionStateLockWrite:void 0,beforeCheckoutLockWrite:void 0,beforeSafeDirectoryCreate:void 0,beforeAtomicTempWrite:void 0,beforeAtomicRename:void 0,openCheckoutLock:defaultPersistenceHooks.openCheckoutLock,removeCheckoutLock:defaultPersistenceHooks.removeCheckoutLock,checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,classifyPrWorkflowGitStateAsync:classifyPrWorkflowGitState,sweepStaleDelegationsAsync:sweepStaleDelegations,probeLaneLivenessAsync:probeAlivePrWorkflowLaneSessions,probeLaneSessionStatusTypesAsync:probePrWorkflowLaneSessionStatusTypes,laneLivenessWatchdog:laneLivenessWatchdogSurface,getSessionOps:defaultGetSessionOps,laneLivenessProbeTimeoutMs:PR_WORKFLOW_LANE_LIVENESS_PROBE_TIMEOUT_MS,pendingLaneLivenessThresholdMs:PR_WORKFLOW_PENDING_LIVENESS_THRESHOLD_MS,effectivePrReviewResiliencePolicy,snapshotPrReviewResiliencePolicy,resolveCurrentGitHead,resolveCurrentGitHeadAsync,resolveCurrentUpstreamPushTarget,resolveCurrentUpstreamPushTargetAsync,resolveCurrentUpstreamRemoteRef,resolveCurrentLocalHeadRefAsync,resolveRemoteUrlIdentity,resolveRemoteUrlIdentityAsync,parseExactBoundPushIntent,admitPrFeedbackPushAttempt,recordPrFeedbackPushAttemptResult,reconcileForeignInFlightAttempt,ensurePublicationGenerationCurrent,invalidatePublicationGeneration,invalidatePrFeedbackPublication,cancelPrFeedbackPublication,buildPublicationEvidenceJoin,nextPublicationContainer,supersedeLivePublicationInPendingState,describePrWorkflowPublicationSection,resolveExactRemoteBranchHead,resolveExactRemoteBranchHeadAsync,resolveCommitCountSince,resolveCommitCountSinceAsync,resolveIsWorkingTreeClean,resolveIsWorkingTreeCleanAsync,resolveIsExactSingleChildCommit,resolveIsExactSingleChildCommitAsync,resolvePrReviewDiffStats,resolvePrReviewDiffStatsAsync,resolvePrWorkflowRevisionDigest,MAX_WORKFLOW_BATCHES,MAX_PR_REVIEW_RESILIENCE_CIRCUIT_CONTRIBUTORS,MAX_RETIRED_REVIEWER_SESSION_IDS,MAX_RETIRED_CONSOLIDATED_LANES,MAX_RETIRED_FEEDBACK_ITEM_OWNERS,resolvePrWorkflowRevisionDigestDetailed,resolveRemoteRefsContainingHead,resolveRemoteRefsContainingHeadAsync,parseCriticVerdict,composePrReviewPhaseVerdicts:async(directory,sessionID,phase)=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return composePrReviewPhaseVerdicts(directory,state,phase,ctx)},assertSettledPhaseHasAuthoritativeVerdicts,derivePrReviewCriticInventoryForCoverageGate:async(directory,sessionID,origin="_test_exports")=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return derivePrReviewCriticInventoryForCoverageGate(directory,state,ctx,origin)},derivePrReviewCandidateInventory:async(directory,sessionID)=>{let state=await requireBoundState2(directory,sessionID,"PR_REVIEW"),ctx=await createPrReviewGateContext2(directory,state);return derivePrReviewCandidateInventory2(directory,state,ctx)},isProcessAlive:defaultPersistenceHooks.isProcessAlive,isSafeStandaloneGitCommit,rename:fsp7.rename,nowMs:()=>Date.now()};Object.assign(_test_exports2,legacyTranscriptAdapterTestSurface);bindPrReviewPersistenceHooks(_test_exports2);bindPrReviewStateCodec({safeParse:(data)=>PrWorkflowGateStateSchema.safeParse(data),parse:(data)=>PrWorkflowGateStateSchema.parse(data)});bindPrReviewCompletionHelpers({createPrReviewGateContext:createPrReviewGateContext2,requireBoundState:requireBoundState2,readPrWorkflowGateStateFromDisk:readPrWorkflowGateStateFromDisk3,readBoundedSwarmRegularFile:readBoundedSwarmRegularFile2,successfulObligationsFromExactBatch:successfulObligationsFromExactBatch2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,validatePrReviewDiscoveryLaneCompletion:validatePrReviewDiscoveryLaneCompletion2,validateExactStructuredReceiptCoverage:validateExactStructuredReceiptCoverage2});bindPrReviewTranscriptAdapterHelpers({derivePrReviewCandidateInventory:derivePrReviewCandidateInventory2,derivePrReviewCriticInventory:derivePrReviewCriticInventory2,authoritativeReviewerClaims:authoritativeReviewerClaims2,reviewerSubagentSessionIds:reviewerSubagentSessionIds2,prReviewPhaseWindow:prReviewPhaseWindow2,batchMayContributeClaims:batchMayContributeClaims2,recordsPassingBatchIntegrity:recordsPassingBatchIntegrity3,loadArtifactPassingLaneIntegrity:loadArtifactPassingLaneIntegrity2});PR_WORKFLOW_SHARED_CONTROLLER_TOOLS=new Set(["abort_pr_workflow","collect_lane_results","complete_pr_workflow","dispatch_lanes_async","prepare_pr_workflow_checkout"]),PR_REVIEW_CONTROLLER_TOOLS=new Set(["authorize_pr_review_reentry","parse_lane_candidates","write_pr_review_artifact","write_pr_review_trigger_eval"]),PR_FEEDBACK_CONTROLLER_TOOLS=new Set(["invalidate_pr_feedback_publication","prepare_pr_feedback_scope","run_pr_feedback_stage_a"]);PR_REVIEW_READ_ONLY_TOOL_NAMES=new Set(["ast_grep_search","codesearch","glob","grep","list","lsp","open","read","search","skill","tree","view","web_fetch","web_search","webfetch","websearch"]);PR_WORKFLOW_CD_PREFIX_PATTERN=/^cd\s+(?:\/d\s+)?(?:"[A-Za-z0-9 _.\\/:~+-]+"|'[A-Za-z0-9 _.\\/:~+-]+'|[A-Za-z0-9_.\\/:~+-]+)\s*&&\s*/i,PR_WORKFLOW_TRAILING_STDERR_MERGE_PATTERN=/\s+2>&1\s*$/,PR_WORKFLOW_GIT_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt](?: -C (?:"[^"]+"|'[^']+'|\S+))* (.+)$/,PR_WORKFLOW_GIT_HAS_DIR_OVERRIDE_PATTERN=/^[Gg][Ii][Tt] -C /;FEEDBACK_NO_CHANGE_CLASSIFICATIONS=new Set(["DISPROVED","PRE_EXISTING","NEEDS_MORE_EVIDENCE","NEEDS_USER_DECISION"])});async function handleAbortPrWorkflowCommand(directory,args2,sessionID){let tokens=(args2??[]).filter((token)=>token.trim().length>0),modeToken=tokens[0]?.toUpperCase(),knownMode=modeToken&&KNOWN_MODES.has(modeToken)?modeToken:void 0,reasonStartIndex=knownMode?1:0,explicitReason=tokens.slice(reasonStartIndex).join(" ").trim().slice(0,500);if(modeToken&&!knownMode)return`Error: Unknown mode "${modeToken}". Expected PR_REVIEW or PR_FEEDBACK.
1260
1261
 
1261
1262
  ${USAGE2}`;if(!sessionID?.trim())return`Error: abort-pr-workflow requires an active sessionID.
1262
1263