opencode-swarm 7.183.0 → 7.183.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 (84) 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/background/pending-delegations.d.ts +21 -1
  4. package/dist/cli/{coder-settlement-6m5stw7s.js → coder-settlement-rserb0hm.js} +10 -10
  5. package/dist/cli/{config-doctor-g6r21wdz.js → config-doctor-r4fmzprn.js} +2 -2
  6. package/dist/cli/{core-6dzx3z8q.js → core-rzek3e2n.js} +3 -3
  7. package/dist/cli/{curation-policy-fm7mtvbk.js → curation-policy-g0jjwrg5.js} +4 -4
  8. package/dist/cli/{curator-drift-art0x91j.js → curator-drift-a0r5krfx.js} +8 -8
  9. package/dist/cli/curator-llm-factory-xp4hgd8r.js +74 -0
  10. package/dist/cli/{curator-0xqj2rxm.js → curator-v84tfqcr.js} +37 -37
  11. package/dist/cli/{evidence-summary-service-h1vb58rd.js → evidence-summary-service-t4csk176.js} +16 -16
  12. package/dist/cli/{gate-evidence-ps3rg5fh.js → gate-evidence-3z04zprn.js} +5 -5
  13. package/dist/cli/guardrail-explain-j2y5sj4d.js +75 -0
  14. package/dist/cli/{guardrail-log-x2gdf8ys.js → guardrail-log-cbzdh4qj.js} +6 -6
  15. package/dist/cli/{guardrail-reset-mwkys4ff.js → guardrail-reset-5e75rz44.js} +37 -37
  16. package/dist/cli/{hive-promoter-gndjyg7e.js → hive-promoter-f54nrhqn.js} +37 -37
  17. package/dist/cli/{index-5cvm6ykc.js → index-08x7gsnf.js} +1 -1
  18. package/dist/cli/{index-1kpa3an2.js → index-0bpr8vag.js} +2 -2
  19. package/dist/cli/{index-a6np52p4.js → index-1hnknn34.js} +3 -3
  20. package/dist/cli/{index-9gehw4xb.js → index-31e105jf.js} +1 -1
  21. package/dist/cli/{index-qws72zbs.js → index-3qy7v4k1.js} +2 -2
  22. package/dist/cli/{index-wnkx6gs0.js → index-3rb5gs4w.js} +1 -1
  23. package/dist/cli/{index-1ex9ecf5.js → index-4hnk9npg.js} +4 -4
  24. package/dist/cli/{index-mewsqwbq.js → index-4xr4gtwd.js} +1 -1
  25. package/dist/cli/{index-s1y70y0w.js → index-5cve9g2b.js} +1 -1
  26. package/dist/cli/{index-r7dqevkc.js → index-5t08vc6m.js} +1 -1
  27. package/dist/cli/{index-7p6s4yfb.js → index-6dm6ettv.js} +1 -1
  28. package/dist/cli/{index-v8ja5zcr.js → index-6h81yvyc.js} +2 -2
  29. package/dist/cli/{index-w6hrms7j.js → index-77650pyg.js} +1 -1
  30. package/dist/cli/{index-r65yxdv7.js → index-80qhm8aq.js} +1 -1
  31. package/dist/cli/{index-yv5fmjcf.js → index-8me6m6ew.js} +2 -2
  32. package/dist/cli/{index-jf9cvkzr.js → index-908k7jhw.js} +3 -3
  33. package/dist/cli/{index-fqc1a1vj.js → index-9f930sy8.js} +2 -2
  34. package/dist/cli/{index-brfs5jqw.js → index-ak1dd17g.js} +3 -3
  35. package/dist/cli/{index-w670pfv4.js → index-b26hje53.js} +5 -5
  36. package/dist/cli/{index-kv0k3b60.js → index-bqphhrwf.js} +5 -5
  37. package/dist/cli/{index-wqg2j647.js → index-bsjwchw7.js} +18 -9
  38. package/dist/cli/{index-v2rbpcqy.js → index-dg3f2sqq.js} +1 -1
  39. package/dist/cli/{index-6f7tfq3m.js → index-gaykghrm.js} +7 -7
  40. package/dist/cli/{index-30pz2xvj.js → index-h01p5ygy.js} +6 -6
  41. package/dist/cli/{index-3bcmw8pc.js → index-hb1zqz50.js} +1 -1
  42. package/dist/cli/{index-wjqc2mnc.js → index-hsvsz3mj.js} +1 -1
  43. package/dist/cli/{index-6nhzekvt.js → index-j8ty457v.js} +2 -2
  44. package/dist/cli/{index-k88thqa0.js → index-jb7ywm4w.js} +6 -6
  45. package/dist/cli/{index-0n24h4zb.js → index-jk05g11c.js} +7 -7
  46. package/dist/cli/{index-29f69hzd.js → index-mt0s67hg.js} +2 -2
  47. package/dist/cli/{index-c6zrffwn.js → index-nazzb4em.js} +75 -75
  48. package/dist/cli/{index-25m6rekr.js → index-nmh0s6dg.js} +1 -1
  49. package/dist/cli/{index-94pwd45k.js → index-qjzbs971.js} +4 -4
  50. package/dist/cli/{index-4aggsva0.js → index-raws06d3.js} +3 -3
  51. package/dist/cli/{index-fb0v3e71.js → index-rhw6m7s9.js} +1 -1
  52. package/dist/cli/{index-ybrwvrd4.js → index-w196wb3a.js} +39 -39
  53. package/dist/cli/{index-820e6w22.js → index-w81jmdkt.js} +2 -2
  54. package/dist/cli/{index-rfggc332.js → index-wpn7ftw1.js} +1 -1
  55. package/dist/cli/{index-jsdnhdzg.js → index-xtysafzj.js} +37 -37
  56. package/dist/cli/{index-pvtf7cjg.js → index-y5hhkx1n.js} +7 -7
  57. package/dist/cli/{index-ht88g5mc.js → index-ydefv5fn.js} +1 -1
  58. package/dist/cli/{index-nmfnggaa.js → index-z425p51d.js} +12 -12
  59. package/dist/cli/index.js +38 -38
  60. package/dist/cli/{knowledge-escalator-gjp71cn2.js → knowledge-escalator-cs7fjgy0.js} +11 -11
  61. package/dist/cli/{knowledge-events-d8k9fmkg.js → knowledge-events-262c1jg2.js} +9 -9
  62. package/dist/cli/{knowledge-link-anzhs41w.js → knowledge-link-8kcms7pj.js} +3 -3
  63. package/dist/cli/{knowledge-store-sqmwvcjd.js → knowledge-store-yjrkfens.js} +4 -4
  64. package/dist/cli/{knowledge-validator-gjqm2zby.js → knowledge-validator-t98cvpt5.js} +6 -6
  65. package/dist/cli/{mcp-phvvtsmt.js → mcp-wj6143vj.js} +1 -1
  66. package/dist/cli/{model-preflight-ehqa8h7x.js → model-preflight-tz4ar9ys.js} +37 -37
  67. package/dist/cli/{pending-delegations-mxs88d0x.js → pending-delegations-vvbkqe24.js} +10 -10
  68. package/dist/cli/{pr-subscriptions-n3ymnt5w.js → pr-subscriptions-maeppcws.js} +10 -10
  69. package/dist/cli/{pr-workflow-gate-t8axhfzw.js → pr-workflow-gate-en54gabv.js} +37 -37
  70. package/dist/cli/{runner-9kd080km.js → runner-618229m8.js} +4 -4
  71. package/dist/cli/{scan-cursor-qg4eg6ah.js → scan-cursor-sxwh1ax8.js} +5 -5
  72. package/dist/cli/{schema-73z5xbmd.js → schema-fb8vm14k.js} +1 -1
  73. package/dist/cli/{scope-persistence-b9924hz1.js → scope-persistence-sc2zhr15.js} +13 -13
  74. package/dist/cli/{server-jn6xd5bh.js → server-7ksq9wr7.js} +37 -37
  75. package/dist/cli/{skill-generator-k344y5m2.js → skill-generator-ccmq47cm.js} +13 -13
  76. package/dist/cli/{snapshot-coordination-init-a8992336.js → snapshot-coordination-init-h8eg88w2.js} +37 -37
  77. package/dist/cli/{speckit-checkoff-0tctprtz.js → speckit-checkoff-vkqn317p.js} +4 -4
  78. package/dist/cli/{workspace-snapshot-7e9me3q7.js → workspace-snapshot-t22m6gbd.js} +3 -3
  79. package/dist/cli/{worktree-collision-ownership-6r6jekr9.js → worktree-collision-ownership-8hr7aycc.js} +11 -11
  80. package/dist/cli/{worktree-isolation-5kw6jnej.js → worktree-isolation-gwq3y9tf.js} +37 -37
  81. package/dist/index.js +4 -4
  82. package/package.json +1 -1
  83. package/dist/cli/curator-llm-factory-grnfsaa2.js +0 -74
  84. package/dist/cli/guardrail-explain-2sb06877.js +0 -75
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.183.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","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
1
+ import{createRequire}from"node:module";var __create=Object.create;var{getPrototypeOf:__getProtoOf,defineProperty:__defProp,getOwnPropertyNames:__getOwnPropNames,getOwnPropertyDescriptor:__getOwnPropDesc}=Object,__hasOwnProp=Object.prototype.hasOwnProperty;function __accessProp(key){return this[key]}var __toESMCache_node,__toESMCache_esm,__toESM=(mod,isNodeMode,target)=>{var canCache=mod!=null&&typeof mod==="object";if(canCache){var cache=isNodeMode?__toESMCache_node??=new WeakMap:__toESMCache_esm??=new WeakMap,cached=cache.get(mod);if(cached)return cached}target=mod!=null?__create(__getProtoOf(mod)):{};let to=isNodeMode||!mod||!mod.__esModule?__defProp(target,"default",{value:mod,enumerable:!0}):target;for(let key of __getOwnPropNames(mod))if(!__hasOwnProp.call(to,key))__defProp(to,key,{get:__accessProp.bind(mod,key),enumerable:!0});if(canCache)cache.set(mod,to);return to},__toCommonJS=(from)=>{var entry=(__moduleCache??=new WeakMap).get(from),desc;if(entry)return entry;if(entry=__defProp({},"__esModule",{value:!0}),from&&typeof from==="object"||typeof from==="function"){for(var key of __getOwnPropNames(from))if(!__hasOwnProp.call(entry,key))__defProp(entry,key,{get:__accessProp.bind(from,key),enumerable:!(desc=__getOwnPropDesc(from,key))||desc.enumerable})}return __moduleCache.set(from,entry),entry},__moduleCache,__commonJS=(cb,mod)=>()=>(mod||cb((mod={exports:{}}).exports,mod),mod.exports);var __returnValue=(v)=>v;function __exportSetter(name,newValue){this[name]=__returnValue.bind(null,newValue)}var __export=(target,all)=>{for(var name in all)__defProp(target,name,{get:all[name],enumerable:!0,configurable:!0,set:__exportSetter.bind(all,name)})};var __esm=(fn2,res)=>()=>(fn2&&(res=fn2(fn2=0)),res);var __require=createRequire(import.meta.url);var package_default;var init_package=__esm(()=>{package_default={name:"opencode-swarm",version:"7.183.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","validate:repo":"bun scripts/ci/repository-validation.ts","drift:check":"bun run scripts/drift-check.ts","check:pre-push":"bun run scripts/drift-check.ts --enforce --no-report && bun run check:registry-citations","schema:generate":"bun run scripts/generate-config-schema.ts","generate:commands-docs":"bun run scripts/generate-commands-docs.ts","check:runtime-src-refs":"bun run scripts/check-runtime-src-refs.ts","drift:fix":"bun run scripts/drift-check.ts --fix --confirm","skills:sync":"bun run scripts/sync-qa-gate-skills.ts",format:"biome format . --write",check:"biome check --write .",dev:"bun run build && opencode","package:smoke":"node scripts/package-smoke.mjs",prepare:"bun run build","repro:704":"node scripts/repro-704.mjs","repro:2669":"node scripts/repro-2669.mjs","repro:2670":"node scripts/repro-2670.mjs","repro:1144":"bun scripts/repro-1144.mjs","repro:1873":"bun build scripts/repro-1873-entry.ts --outdir dist-build-test/repro-1873 --target node --format esm && node scripts/repro-1873.mjs","repro:2487":"bun build scripts/repro-2487-parity-entry.ts --outdir dist-build-test/repro-2487 --target node --format esm && node scripts/repro-2487-parity.mjs","check:events":"bun run scripts/check-event-contract.ts","check:retention":"bun run scripts/check-retention-registry.ts","check:core-events":"bun run scripts/check-core-events-usage.ts","check:shell-audit":"bun run scripts/check-shell-audit-usage.ts","check:trajectory-store":"bun run scripts/check-trajectory-store-usage.ts","check:mock-cleanup":"bun run scripts/check-mock-cleanup.ts","check:invariants":"bun run scripts/check-invariants.ts","check:token-formula":"bun run scripts/check-token-formula.ts","check:cross-contamination":"bun run scripts/check-cross-contamination.ts","check:test-clock":"bun run scripts/check-test-clock.ts","check:test-file-cap":"bun run scripts/check-test-file-cap.ts","check:test-tmpdir":"bun run scripts/check-test-tmpdir.ts","check:bash-portability":"bun run scripts/check-bash-portability.ts","check:pending-fragment":"bun run scripts/check-pending-fragment.ts","check:gate-portability":"bun run scripts/check-gate-portability.ts","check:bare-spawn":"bun run scripts/check-bare-executable-spawn.ts","check:error-channel-discard":"bun run scripts/check-error-channel-discard.ts","check:path-identity":"bun run scripts/check-path-identity.ts","check:registry-citations":"bun run scripts/check-registry-citations.ts","check:memory-recall":"bun run scripts/memory-recall-regression.ts","check:retrieval-quality":"bun run scripts/retrieval-quality-regression.ts"},dependencies:{"@modelcontextprotocol/sdk":"^1.30.0","@opencode-ai/plugin":"^1.18.3","@opencode-ai/sdk":"^1.18.3","@vscode/tree-sitter-wasm":"^0.3.0","bash-parser":"^0.5.0","p-limit":"^7.3.0",picomatch:"^4.0.4","proper-lockfile":"^4.1.2","quick-lru":"^7.3.0","web-tree-sitter":"^0.25.0",zod:"4.3.6"},devDependencies:{"@biomejs/biome":"2.3.14","@types/picomatch":"^4.0.3","bun-types":"1.3.8","js-yaml":"^4.1.1",typescript:"^5.7.3"},peerDependencies:{"@xenova/transformers":"^2.17.2"},peerDependenciesMeta:{"@xenova/transformers":{optional:!0}}}});var QA_AGENTS,PIPELINE_AGENTS,ORCHESTRATOR_NAME="architect",ALL_SUBAGENT_NAMES,ALL_AGENT_NAMES;var init_agent_names=__esm(()=>{QA_AGENTS=["reviewer","critic","critic_oversight","critic_finding_validator"],PIPELINE_AGENTS=["explorer","coder","test_engineer"],ALL_SUBAGENT_NAMES=["sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","curator_postmortem","curator_consolidation","council_generalist","council_skeptic","council_domain_expert","skill_improver","spec_writer",...QA_AGENTS,...PIPELINE_AGENTS],ALL_AGENT_NAMES=["architect",...ALL_SUBAGENT_NAMES]});function getPrWorkflowToolCapability(toolName,mode){let metadata=TOOL_METADATA[toolName];if(!metadata?.prWorkflow?.modes.includes(mode))return null;return metadata.prWorkflow.capability}var TOOL_METADATA,TOOL_NAMES,TOOL_NAME_SET,TOOL_DESCRIPTIONS,AGENT_TOOL_MAP;var init_tool_metadata=__esm(()=>{init_agent_names();TOOL_METADATA={diff:{description:"structured git diff with contract change detection",agents:["architect","reviewer","critic_finding_validator","critic_oversight","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},diff_summary:{description:"filter classified AST changes by category, risk level, or file for reviewer drill-down",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},syntax_check:{description:"check syntax of source files using tree-sitter parsers across multiple languages, returning per-file errors",agents:["architect","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},placeholder_scan:{description:"todo and FIXME comment detection",agents:["architect","reviewer","critic_finding_validator"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},imports:{description:"find all consumers that import from a given file — use before refactoring shared modules to avoid breaking unseen dependents",agents:["architect","sme","researcher","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},lint:{description:"run project linter in check or fix mode; supports biome, eslint, ruff, clippy, and more, returns structured results",agents:["architect","reviewer","critic_finding_validator","coder"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},secretscan:{description:"scan for secrets (API keys, tokens, passwords) via regex and entropy; returns redacted previews, excludes common dirs",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},sast_scan:{description:"static analysis security scan",agents:["architect","reviewer","critic_finding_validator","critic_oversight"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},build_check:{description:"discover and run build, typecheck, and test commands for various project ecosystems in the working directory",agents:["architect","coder","test_engineer"]},pre_check_batch:{description:"parallel verification: lint:check + secretscan + sast_scan + quality_budget",agents:["architect","reviewer","critic_finding_validator"]},quality_budget:{description:"code quality budget check",agents:["architect"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},symbols:{description:"extract exported symbols (functions, classes, interfaces, types) from source files; supports TypeScript, JavaScript, and Python",agents:["architect","sme","researcher","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},complexity_hotspots:{description:"git churn × complexity risk map",agents:["architect","sme","researcher","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","reviewer","critic_finding_validator","critic","critic_oversight","explorer","test_engineer"]},schema_drift:{description:"OpenAPI spec vs route drift",agents:["architect","sme","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},todo_extract:{description:"structured TODO/FIXME extraction",agents:["architect","researcher","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},evidence_check:{description:"verify task evidence completeness",agents:["architect","critic_oversight"]},check_gate_status:{description:"check the gate status of a specific task",agents:["architect","critic_oversight"]},completion_verify:{description:"verify completed tasks have required evidence",agents:["architect","critic_oversight"]},complete_pr_workflow:{description:"validate terminal PR workflow evidence and clear its durable session gate",agents:["architect"]},abort_pr_workflow:{description:"abort an unrecoverable PR_REVIEW/PR_FEEDBACK mechanical gate and clear its durable session state",agents:["architect"]},authorize_pr_review_reentry:{description:"issue a one-use, identity-bound reviewer/test_engineer re-entry authorization for the active PR_REVIEW workflow (issue #2383)",agents:["architect"]},submit_pr_review_result:{description:"submit one child-bound typed result for an active PR-review base or micro discovery lane",agents:[],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},approve_plan_critic:{description:"record a MANUAL plan_critic_gate approval snapshot to unblock the ratchet-tighter critic_pre_plan execution gate when the critic already returned APPROVED but the mechanical recorder failed to persist it (issue #2012), or as the sanctioned recovery for a bookkeeping-grade hashed-field repair under the critic-gate PLAN FREEZE rule (the reason must state which case applies)",agents:["architect"]},approve_retry_sounding_board:{description:"record a MANUAL critic_sounding_board gate entry to unblock the coder retry circuit-breaker gate when the sounding board returned APPROVED but the mechanical recorder missed it (issue #2703)",agents:["architect"]},recover_rework_task:{description:"recover a task wedged at rework_required when the reviewer/test_engineer verdict did not require a code change: write a supervised stage_a_passed so those gates can be re-dispatched without re-running the coder (issue #2755)",agents:["architect"]},prepare_pr_workflow_checkout:{description:"prepare an auditable PR workflow checkout or restore its exact original branch/HEAD and preserved stash after terminal cleanup",agents:["architect"]},invalidate_pr_feedback_publication:{description:"invalidate the armed PR_FEEDBACK publication generation so approved content can change, superseding every content-dependent approval and reopening the exact scoped rework + fresh-review path (issue #2108)",agents:["architect"]},record_implementation_review:{description:"record fresh-context reviewer + critic APPROVE verdicts for the implementation diff so the /swarm issue --trace workflow can satisfy its review gate before commit-pr handoff",agents:["architect"]},record_issue_publication:{description:"record a publication receipt so the /swarm issue --trace workflow reaches its terminal published state after the PR is created/updated",agents:["architect"]},record_issue_reproduction:{description:"record the reproduction outcome for the current traced issue so the /swarm issue --trace workflow can satisfy its reproduction gate and transition to PLAN",agents:["architect"]},record_recurrence_sweep:{description:"record the recurrence sweep (defect class, predicates, hit dispositions, guardrail proof, related-problems results) so the /swarm issue --trace workflow can satisfy its recurrence gate before commit-pr handoff",agents:["architect"]},record_branch_freshness:{description:"record the Phase 0 branch-freshness outcome (synced / behind:<n> / fetch-failed:<reason> plus optional user override) so the /swarm issue --trace workflow can pass its freshness gate before transitioning to PLAN (issue #2564)",agents:["architect"]},record_trace_validation:{description:"record one per-phase trace-check.sh validator outcome (phase, pass/fail, reviewedCommit, treeId) so the /swarm issue --trace workflow can satisfy its validator-receipt gate before commit-pr handoff (issue #2564)",agents:["architect"]},record_merge_approval:{description:"record the human merge approval bound to the exact PR head SHA so the /swarm issue --trace workflow reaches its terminal merge_approval_recorded state — recorded for audit only, never certified or driven by the plugin (issue #2564)",agents:["architect"]},rebind_pr_feedback_head:{description:"rebind a PR_FEEDBACK workflow to a new verified remote PR head after merge/rebase/conflict repair, invalidating ancestry-bound receipts so the mechanical ladder re-runs",agents:["architect"]},run_pr_feedback_stage_a:{description:"execute and persist mandatory PR-feedback Stage A checks on a content-bound revision",agents:["architect"]},submit_council_verdicts:{description:"submit pre-collected council member verdicts for synthesis (architect MUST dispatch critic/reviewer/sme/test_engineer/explorer as Agent tasks first; this tool synthesizes only, it does not contact members)",agents:[]},submit_phase_council_verdicts:{description:"submit pre-collected phase-level council member verdicts for holistic phase synthesis (architect MUST dispatch all 5 council members with phase-scoped context first; this tool synthesizes only, it does not contact members)",agents:[]},declare_council_criteria:{description:"pre-declare acceptance criteria for a task before the coder starts work; criteria are read back during council evaluation",agents:[]},sbom_generate:{description:"SBOM generation for dependency inventory",agents:["architect"]},checkpoint:{description:"create named git checkpoints for save, restore, and delete — use before risky operations to enable rollback",agents:["architect"]},pkg_audit:{description:"dependency vulnerability scan — npm/pip/cargo",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},parse_lane_candidates:{description:"Parse [CANDIDATE] rows from a dispatch_lanes or collect_lane_results artifact (by output_ref), produce structured records with provenance, optionally persist to a per-batch sidecar JSONL. Pure-parser variant exists as internal module.",agents:["architect"]},plan_conflict_check:{description:"read-only advisory check (#1656): compute a pairwise file-conflict matrix for N proposed parallel task groups using declared scopes and optional git co-change; returns a verdict (all_disjoint / conflicts_present / unknown_scopes), per-pair evidence, and a suggested serialization order. Writes nothing — the execution gate independently recomputes the verdict inline at dispatch time via the same helper. Call BEFORE attempting parallel dispatch to confirm disjointness.",agents:["architect"]},write_pr_review_trigger_eval:{description:"persist the complete PR-review trigger evaluation with exact-set validation, dispatch provenance, and live merge-base verification",agents:["architect"]},write_pr_review_artifact:{description:"persist schema-validated PR-review findings checkpoints and exact actionable feedback handoffs under the active run",agents:["architect"]},prepare_pr_feedback_scope:{description:"prepare an exact file scope for one PR-feedback coder Task after immutable feedback verification settles",agents:["architect"]},test_runner:{description:"auto-detect and run tests",agents:["architect","reviewer","critic_finding_validator","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},test_impact:{description:"identify test files impacted by changed source files via import analysis",agents:["architect","reviewer","critic_finding_validator","critic_oversight","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},mutation_test:{description:"executes pre-generated mutation patches against tests, evaluates kill rate against quality gate thresholds; test selection comes from explicit files (override) or source_files derived via the impact analyzer with a typed bounded fallback",agents:["architect","test_engineer"]},generate_mutants:{description:"generate LLM-based mutation testing patches for source files; returns MutationPatch[] for direct consumption by the mutation_test tool",agents:["architect"]},detect_domains:{description:"detect which SME domains are relevant for a given text",agents:["architect","sme","docs","docs_design","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic","critic_oversight","explorer"]},git_blame:{description:"per-line git blame metadata: sha, author, date, summary for each line in a file",agents:["reviewer","critic_finding_validator","explorer","architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},gitingest:{description:"fetch a GitHub repository full content via gitingest.com",agents:["architect","docs","explorer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_summary:{description:"retrieve the full content of a stored tool output summary",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},retrieve_lane_output:{description:"retrieve paged full dispatch lane output by output_ref; use before consuming truncated lane previews or routing candidates from lane results",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},extract_code_blocks:{description:"extract code blocks from text content and save them to files",agents:["docs","docs_design","designer","spec_writer","coder","test_engineer"]},phase_complete:{description:"preflight every applicable phase gate, report all blockers, and atomically commit a current passing snapshot",agents:["architect"]},run_phase_review:{description:"run the bounded phase-final review engine and persist complete content-addressed review evidence",agents:["architect"]},repair_gate_evidence:{description:"quarantine recoverable exact-task gate evidence, rebuild from durable requirements, recover receipt-backed legacy marker wedges or the exact sentinel-only historical reset, and refuse every other receipt-less reconstruction",agents:["architect"]},repair_knowledge_receipt_ledger:{description:"validate or repair authoritative knowledge receipts, preserve corrupt authority in bounded quarantine, and require scoped re-evaluation",agents:["architect"]},record_directive_override:{description:"record an audited architect override for identified critical-directive violations without bypassing unreadable authority",agents:["architect"]},save_plan:{description:"save a structured implementation plan",agents:["architect"]},update_task_status:{description:"mark tasks complete, track phase progress",agents:["architect"]},lint_spec:{description:"validate .swarm/spec.md format and required fields",agents:["architect","spec_writer"]},write_retro:{description:"document phase retrospectives via phase_complete workflow, capture lessons learned",agents:["architect"]},write_drift_evidence:{description:"write drift verification evidence for a completed phase",agents:["architect"]},write_hallucination_evidence:{description:"write hallucination verification evidence for a completed phase",agents:["architect"]},write_mutation_evidence:{description:"write mutation gate evidence for a completed phase; normalizes PASS/WARN/FAIL/SKIP verdicts and writes .swarm/evidence/{phase}/mutation-gate.json",agents:["architect"]},declare_scope:{description:"declare file scope for next coder delegation",agents:["architect"]},scope_validate:{description:"validate shell writes against an inline file scope",agents:["architect"]},knowledge_query:{description:"query swarm or hive knowledge with optional filters",agents:["architect","skill_improver","spec_writer"]},doc_scan:{description:"scan project documentation files and build an index manifest",agents:["architect","docs_design","skill_improver","spec_writer","explorer"]},doc_extract:{description:"extract actionable constraints from project documentation",agents:["architect","docs_design","skill_improver","spec_writer"]},curator_analyze:{description:"run curator phase analysis and optionally apply knowledge recommendations",agents:["architect"]},consensus_mine:{description:"mine cross-run consensus from existing .swarm evidence into an immutable proposals-only report; also deletes its own reports past consensus.report_retention, appends to the shared recommendation dedup ledger (in the shared cohort root, outside this project, when a knowledge link is active), and mirrors proposals into pending swarm-memory proposals when memory is enabled",agents:["architect","curator_phase","curator_postmortem"]},knowledge_add:{description:"store a new lesson in the knowledge base",agents:["architect","coder"]},knowledge_recall:{description:"search the knowledge base for relevant past decisions",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"]},knowledge_remove:{description:"delete an outdated swarm knowledge entry by ID (swarm tier only)",agents:["architect"]},co_change_analyzer:{description:"detect hidden couplings by analyzing git history",agents:["architect"]},context_status:{description:"report current context-window headroom for the active session — returns tokens-used, usageSource (provider|estimated), model-limit with provenance (modelLimitSource: host|override|provider_cap|native|fallback; modelLimitResolution: user_provider_model|user_model|user_default|live_model_limit|static_provider_cap|static_native|static_default; fallbackActive: true when the denominator came from a static table or the flat 128k default — treat headroom as uncertain), usage-percent, threshold-state (none/warn/critical), model name, and provider. Pure read-only: no state mutation, no warning injection. Works whether context_budget.enabled is true or false.",agents:["architect"]},search:{description:"Workspace-scoped ripgrep-style text search with structured JSON output. Supports literal and regex modes, glob filtering, and result limits. NOTE: This is text search, not structural AST search — use symbols and imports tools for structural queries.",agents:["architect","sme","docs","docs_design","designer","critic_hallucination_verifier","skill_improver","spec_writer","reviewer","critic_finding_validator","critic_oversight","explorer","coder","test_engineer","researcher"]},ast_grep:{description:"Read-only structural AST search using ast-grep patterns with optional language and glob filters. Use for syntax-aware code pattern searches; does not rewrite files.",agents:["architect","sme","docs","docs_design","critic_hallucination_verifier","spec_writer","explorer","coder","test_engineer","researcher"]},actionlint_scan:{description:"Run actionlint against GitHub Actions workflow YAML files with structured findings. Resolves actionlint lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},osv_scan:{description:"Run OSV-Scanner against a workspace path and return structured dependency vulnerability findings. Resolves osv-scanner lazily and does not modify files.",agents:["architect","test_engineer"],prWorkflow:{modes:["PR_REVIEW"],capability:"validate"}},gh_evidence:{description:"Fetch bounded GitHub pull request or issue metadata through gh for review and CI evidence. Resolves gh lazily and is read-only.",agents:["architect","researcher"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},pr_workflow_status:{description:"Read-only architect observation of local git state (HEAD, branch, clean/dirty with a bounded changed-file list, remotes) plus a session-pinned PR workflow gate summary and the PR_FEEDBACK publication-generation section (state, attempts, invalidation reason, recovery guidance). Use to observe state under the fail-closed PR_REVIEW/PR_FEEDBACK gate. Never executes PR-controlled scripts and never reads another session gate.",agents:["architect"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},batch_symbols:{description:"Batched symbol extraction across multiple files. Returns per-file symbol summaries with isolated error handling.",agents:["architect","critic_hallucination_verifier","reviewer","critic_finding_validator","critic_oversight","explorer"]},suggest_patch:{description:"Reviewer-safe structured patch suggestion tool. Produces context-anchored patch artifacts without file modification. Returns structured diagnostics on context mismatch.",agents:["architect","reviewer","critic_finding_validator"]},req_coverage:{description:"query requirement coverage status for tracked functional requirements",agents:["critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","spec_writer","critic","critic_oversight"]},get_approved_plan:{description:"retrieve the last critic-approved immutable plan snapshot for baseline drift comparison",agents:["critic_drift_verifier","critic","critic_oversight"]},repo_map:{description:"query the repo code graph: importers, dependencies, blast radius, localization, ontology facts, package boundaries, and heuristic preflight packets before refactoring; ontology findings are advisory, not formal proofs",agents:["architect","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","reviewer","critic_finding_validator","critic","critic_oversight","explorer","coder","test_engineer"],prWorkflow:{modes:["PR_REVIEW","PR_FEEDBACK"],capability:"observe"}},get_qa_gate_profile:{description:"retrieve the QA gate profile for the current or exact future plan identity: gates (reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council), lock state, profile hash, the calling session’s ratchet-tighter overrides, and the EFFECTIVE gates (profile merged with those overrides; durable across restart). Read-only and never creates state.",agents:["architect"]},set_qa_gates:{description:"configure the QA gate profile for the current plan or bootstrap an exact future plan with swarm_id and plan_title. Architect-only. The initial selection may set explicit true/false values over defaults; later changes are ratchet-tighter and rejected once locked after critic approval. Supports: reviewer, test_engineer, sme_enabled, critic_pre_plan, sast_enabled, council_mode, hallucination_guard, mutation_test, phase_council, drift_check, final_council, plus adopt_legacy_binding_only for exact-binding recovery without mutating gates.",agents:["architect"]},web_search:{description:"External web search (Tavily or Brave) for architect-driven council research, SME domain research, researcher auto-research, and skill-improver research. Returns titled results with snippets, URLs, normalized query metadata, temporal intent, freshness, and removed stale years. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides. Requires a search API key. Used by the architect in MODE: COUNCIL to gather a RESEARCH CONTEXT before dispatching council agents, by SME for opt-in external skill/source evaluation, and by the researcher agent for multi-source auto-research.",agents:["sme","researcher","skill_improver"]},web_fetch:{description:"Fetch the readable text of a single http(s) URL (architect-only). Returns decoded page text, document title, final URL after redirects, and an evidence reference. Reads primary sources that web_search only surfaces as snippets. Config-gated on council.general.enabled. Blocks private/loopback/link-local/metadata addresses (re-validated and re-pinned across redirects); enforces timeout and body size cap.",agents:[]},convene_general_council:{description:"Synthesize responses from a multi-model General Council. Accepts parallel member responses (Round 1, optionally Round 2), detects disagreements, and returns consensus points, persisting disagreements, and a structured synthesis. Architect-only. Config-gated on council.general.enabled in the resolved config: global ~/.config/opencode/opencode-swarm.json, then project .opencode/opencode-swarm.json overrides.",agents:[]},write_final_council_evidence:{description:"Persist project-scoped final council evidence to .swarm/evidence/final-council.json. PREREQUISITE: dispatch critic, reviewer, sme, test_engineer, and explorer as project-scoped Agent tasks and collect their CouncilMemberVerdict JSON — this tool synthesizes only. Rejects on insufficient quorum or CONCERNS with unresolved requiredFixes; normalizes verdicts to approved/concerns/rejected. Architect-only.",agents:[]},skill_generate:{description:"compile knowledge entries into a structured SKILL.md draft",agents:["skill_improver"]},skill_list:{description:"list generated skill files and their status",agents:["skill_improver"]},skill_apply:{description:"activate a draft skill proposal",agents:[]},skill_inspect:{description:"inspect the content and source entries of a skill file",agents:["skill_improver"]},run_stale_reconciliation:{description:"reconcile skills against the knowledge store: mark skills stale when source knowledge is archived or deleted, or clear stale markers",agents:["architect"]},skill_regenerate:{description:"regenerate an active skill by re-clustering its source knowledge entries and updating the SKILL.md in place",agents:[]},skill_retire:{description:"retire a generated skill by adding a retired.marker file; retired skills are excluded from scoring and injection",agents:[]},skill_improve:{description:"run the skill_improver agent to review and refine skills",agents:["skill_improver"]},spec_write:{description:"author or update .swarm/spec.md for the current project",agents:["spec_writer"]},knowledge_receipt:{description:"file a receipt for retrieved knowledge (applied/ignored/contradicted + new lessons), recorded as immutable knowledge events",agents:["architect","sme","docs","docs_design","designer","critic_sounding_board","critic_drift_verifier","critic_hallucination_verifier","critic_architecture_supervisor","curator_init","curator_phase","skill_improver","spec_writer","reviewer","critic_finding_validator","critic","coder","test_engineer"]},knowledge_receipt_status:{description:"receipt status",agents:["architect"]},knowledge_archive:{description:"archive (default), quarantine, or purge a swarm or hive knowledge entry by ID with an immutable audit tombstone; purge requires an admin flag",agents:["architect"]},swarm_memory_recall:{description:"recall scoped Swarm memory for the current repository as untrusted background",agents:[]},swarm_memory_propose:{description:"create a pending Swarm memory proposal; does not write durable memory directly",agents:[]},swarm_memory_outcome:{description:"record useful, dead-end, or corrected outcomes and, when enabled, synchronously refresh deterministic memory lessons",agents:[]},swarm_command:{description:"run supported /swarm commands through the canonical command registry",agents:["architect","sme","researcher","docs","docs_design","designer","reviewer","critic_finding_validator","critic","explorer","coder","test_engineer"]},dispatch_lanes:{description:"dispatch read-only exploration/review lanes concurrently and BLOCK until all finish; prefer dispatch_lanes_async for non-blocking dispatch, use this only when promptAsync is unavailable",agents:["architect"]},dispatch_lanes_async:{description:"launch read-only advisory lanes non-blockingly and return a batch id plus lane session handles immediately; each lane agent must be a registered generated agent name (unregistered bare roles are refused on multi-swarm hosts); launch_timeout_ms is only a promptAsync acceptance budget, not a lane runtime timeout; poll incrementally with collect_lane_results (wait omitted), or join with wait: true for all results",agents:["architect"]},collect_lane_results:{description:"collect/poll a dispatch_lanes_async batch; a presumed-stale sweep runs on every call, settling lanes past the horizon: idle host to stale, unobservable host to a typed liveness error; cancel_pending cancels pending lanes; otherwise observe-only. Non-blocking poll (wait omitted or false) and blocking join (wait: true) supported. The wait budget bounds the observer call only — expiry never kills a lane nor proves it died; poll again or cancel explicitly, never abort. Unsettled lanes are reported in pending_lanes (batch_id, lane_id, status, output_ref) regardless of include_pending; busy/retry lanes never go stale for running long. Does not advance workflow gates. Settled-lane inline output is delivered once: later polls set output_omitted_repeat: true and omit output but keep output_ref for retrieval via retrieve_lane_output.",agents:["architect"]},summarize_work:{description:"emit a short structured summary of completed work (key decisions, assumptions, risks, constraints) at task completion; rolls up per phase for architecture-supervisor review. Advisory, never blocks.",agents:["architect","sme","researcher","docs","docs_design","designer","explorer","coder","test_engineer"]},write_architecture_supervisor_evidence:{description:"persist the architecture supervisor verdict for a phase (architect MUST dispatch critic_architecture_supervisor first and collect its JSON verdict; this tool persists only, it does not contact the supervisor)",agents:["architect"]},lean_turbo_plan_lanes:{description:"partition phase tasks into parallel lanes based on file-scope conflicts for Lean Turbo execution",agents:[]},lean_turbo_acquire_locks:{description:"acquire file locks for all files in a lane (all-or-nothing) before lane execution",agents:[]},lean_turbo_runner_status:{description:"read Lean Turbo run state from .swarm/turbo-state.json",agents:[]},lean_turbo_critic:{description:"dispatch a read-only critic agent to evaluate boundary conditions for a completed Lean Turbo phase (satisfies the turbo.lean.phase_critic gate)",agents:[]},lean_turbo_review:{description:"dispatch a read-only reviewer agent to evaluate a completed Lean Turbo phase",agents:[]},lean_turbo_run_phase:{description:"Execute a phase using Lean Turbo parallel lane execution. Plans lanes, acquires file locks, and dispatches coder agents concurrently. Use when Lean Turbo is active and you want to execute all tasks in a phase in parallel lanes.",agents:[]},lean_turbo_status:{description:"returns Lean Turbo configuration and active status for the current session",agents:[]},swarm_apply_patch:{description:"Apply a unified diff patch to workspace files with exact context matching, atomic writes, and path validation. Use standard unified diff format only — does NOT support *** Begin Patch / *** Update File payloads (use native apply_patch for those).",agents:["coder","test_engineer"]},external_skill_discover:{description:"Discover external skill candidates from configured sources. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_list:{description:"List external skill candidates in the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_inspect:{description:"Inspect a specific external skill candidate by ID. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_promote:{description:"Promote a validated external skill candidate to an active generated skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_reject:{description:"Reject an external skill candidate after evaluation. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_delete:{description:"Delete an external skill candidate from the quarantine store. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},external_skill_revoke:{description:"Revoke a previously promoted external skill. Returns a disabled message when external_skills.curation_enabled is false.",agents:[]},epic_decide_phase:{description:"Compute the Epic Mode verdict for a phase WITHOUT dispatching coders. Runs preflight + calibration + the three gates (p-threshold, hot-module, greenfield), persists the decision, and returns the verdict so the architect can dispatch waves via the visible Task tool (promote) or fall back to per-task serial (demote). Pair with `epic_plan_waves` to get the wave plan when promoted. Use when /swarm epic is on for the session.",agents:["architect"]},epic_plan_waves:{description:"Partition a phase's pending tasks into ordered concurrent waves for Epic Mode dispatch. A wave is a set of tasks with mutually disjoint declared scopes and all dependencies satisfied by prior waves. Returns `{ waves: [{ waveId, taskIds, files }, ...], serializedTasks, degradedTasks }`. "+'For each wave in order, the architect dispatches one `Task(subagent_type="coder", ...)` per `taskId` — all in one assistant message — so the wave runs concurrently and each coder appears as a visible subagent. '+"Wait for the wave to finish before dispatching the next. Pair with `epic_decide_phase` (called first; this tool is only relevant on a `promote` verdict). "+"Preflight reject reasons: `no-plan`, `no-phase`, `phase-empty`, `phase-already-complete`, `scopes-missing` (call `declare_scope` for `missingScopes`), `git-failed` (transient — retry), `planner-error`.",agents:["architect"]},epic_record_divergence:{description:"After every `update_task_status(completed)`, record the task's declared-vs-actual divergence to .swarm/epic/divergence.jsonl. Feeds Epic Mode's self-calibration loop (Capability D). Best-effort: never blocks.",agents:["architect"]}},TOOL_NAMES=Object.keys(TOOL_METADATA),TOOL_NAME_SET=new Set(TOOL_NAMES);TOOL_DESCRIPTIONS=Object.fromEntries(Object.entries(TOOL_METADATA).map(([name,meta])=>[name,meta.description])),AGENT_TOOL_MAP=(()=>{let map=Object.fromEntries(ALL_AGENT_NAMES.map((agent)=>[agent,[]]));for(let[name,meta]of Object.entries(TOOL_METADATA))for(let agent of meta.agents)map[agent].push(name);return map})()});function scanOverrideForDangerousKeys(value,path,depth){if(depth>=10)return;if(Array.isArray(value)){for(let i=0;i<value.length;i++)scanOverrideForDangerousKeys(value[i],`${path}[${i}]`,depth+1);return}if(typeof value!=="object"||value===null)return;for(let key of Object.keys(value)){if(DANGEROUS_MERGE_KEYS.has(key))throw new DangerousMergeKeyError(key,path);scanOverrideForDangerousKeys(value[key],`${path}.${key}`,depth+1)}}function deepMergeInternal(base,override,depth,path){if(depth>=10)throw Error("deepMerge exceeded maximum depth of 10");let result={...base};for(let key of Object.keys(override)){let baseVal=base[key],overrideVal=override[key];if(typeof baseVal==="object"&&baseVal!==null&&typeof overrideVal==="object"&&overrideVal!==null&&!Array.isArray(baseVal)&&!Array.isArray(overrideVal))result[key]=deepMergeInternal(baseVal,overrideVal,depth+1,`${path}.${key}`);else result[key]=overrideVal}return result}function deepMerge(base,override){if(!base)return override;if(!override)return base;return scanOverrideForDangerousKeys(override,"$",0),deepMergeInternal(base,override,0,"$")}var MAX_MERGE_DEPTH=10,DANGEROUS_MERGE_KEYS,DangerousMergeKeyError;var init_merge=__esm(()=>{DANGEROUS_MERGE_KEYS=new Set(["__proto__","constructor","prototype"]);DangerousMergeKeyError=class DangerousMergeKeyError extends Error{key;path;constructor(key,path){super(`deepMerge refused dangerous key "${key}" at "${path}": prototype-pollution carriers (__proto__/constructor/prototype) are never merged`);this.key=key;this.path=path;this.name="DangerousMergeKeyError"}}});function freezeSet(items,name="CLAUDE_CODE_NATIVE_COMMANDS"){let set=new Set(items),proxy=new Proxy(set,{get(target,prop){if(prop==="add"||prop==="delete"||prop==="clear")return()=>{throw TypeError(`${name} is readonly`)};if(prop==="forEach")return(callback,thisArg)=>{let wrapped=(v,k)=>callback.call(thisArg??void 0,v,k,proxy);return set.forEach(wrapped)};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value},set(){throw TypeError(`${name} is readonly`)},deleteProperty(){throw TypeError(`${name} is readonly`)},defineProperty(){throw TypeError(`${name} is readonly`)},setPrototypeOf(){throw TypeError(`${name} is readonly`)}});return proxy}function isQAAgent(name){return QA_AGENTS.includes(name)}function isSubagent(name){return ALL_SUBAGENT_NAMES.includes(name)}function isLowCapabilityModel(modelId){let lower=(modelId||"").toLowerCase();return LOW_CAPABILITY_MODELS.some((substr)=>lower.includes(substr))}var OPENCODE_NATIVE_AGENTS,CLAUDE_CODE_NATIVE_COMMANDS,OPENCODE_NATIVE_COMMANDS,MEMORY_AGENT_TOOL_MAP,EXTERNAL_SKILL_TOOL_NAMES,EXTERNAL_SKILL_AGENT_TOOL_MAP,COUNCIL_TOOL_NAMES,COUNCIL_AGENT_TOOL_MAP,GENERAL_COUNCIL_TOOL_NAMES,GENERAL_COUNCIL_AGENT_TOOL_MAP,TURBO_TOOL_NAMES,TURBO_AGENT_TOOL_MAP,SKILL_TOOL_NAMES,SKILL_AGENT_TOOL_MAP,PR_REVIEW_CHILD_TOOL_NAMES,PR_REVIEW_CHILD_AGENT_TOOL_MAP,WRITE_TOOL_NAMES,SUMMARIZER_EXEMPT_TOOL_NAMES,DEFAULT_MODELS,DEFAULT_AGENT_CONFIGS,DEFAULT_SCORING_CONFIG,LOW_CAPABILITY_MODELS,TURBO_MODE_BANNER=`## \uD83D\uDE80 TURBO MODE ACTIVE
2
2
 
3
3
  **Speed optimization enabled for this session.**
4
4
 
@@ -176,7 +176,7 @@ line break`,"required change with\rcarriage return"]),discardedReviewer=encodePr
176
176
  `);return outside?`${outside}
177
177
  ${protocol}`:protocol}function declaredCanonicalFamilies(source){let families=[];for(let line of source.split(/\r?\n/)){let family=candidateHeaderFamily(splitPipeFields(line).map((field)=>field.trim()));if(family&&!families.includes(family))families.push(family)}return families}function normalizeCandidateArtifact(rawText,fallbackFamily){let repairKinds=[],summaryDrop=dropNonContractMarkerRows(rawText);if(summaryDrop.dropped)repairKinds.push("summary-row-dropped");let recoveredFence=recoverTerminalProtocolFence(summaryDrop.text,fallbackFamily);if(recoveredFence!==null)repairKinds.push("terminal-protocol-fence");let cleanRepair=repairRedundantCleanConfidence(recoveredFence??removeCandidateCodeFences(summaryDrop.text),fallbackFamily);if(cleanRepair.repaired)repairKinds.push("redundant-clean-confidence");let pipeRepair=repairCleanEvidencePipes(cleanRepair.text);if(pipeRepair.repaired)repairKinds.push("clean-evidence-pipe-tail-merge");let candidatePipeRepair=repairCandidateEvidencePipes(pipeRepair.text,fallbackFamily);if(candidatePipeRepair.repaired)repairKinds.push("candidate-evidence-pipe-recovery-lossy");let lateHeaderRepair=resynchronizeLateCanonicalHeader(candidatePipeRepair.text,fallbackFamily);if(lateHeaderRepair.repaired)repairKinds.push("late-canonical-header-resynchronized");let duplicateHeaderDrop=dropDuplicateHeaderRows(lateHeaderRepair.text);if(duplicateHeaderDrop.dropped)repairKinds.push("duplicate-header-row-dropped");let text=duplicateHeaderDrop.text,header=selectCandidateHeader(text.split(/\r?\n/));if(header?.markerBearing&&header.family!==null)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(text).length>0)return{text,synthesizedHeader:!1,repairKinds};if(declaredCanonicalFamilies(summaryDrop.text).some((family)=>family!==fallbackFamily))return{text,synthesizedHeader:!1,repairKinds};let lines=text.split(/\r?\n/);if(!lines.some((line)=>{if(analyzeCandidateLine(line,fallbackFamily)?.valid===!0)return!0;let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!==CLEAN_MARKER)return!1;return analyzeCleanFields(fields,fallbackFamily).valid}))return{text,synthesizedHeader:!1,repairKinds};let firstSalvageableIndex=lines.findIndex((line)=>{let marker=splitPipeFields(line)[0]?.trim();return marker===CANDIDATE_MARKER||marker===CLEAN_MARKER});return repairKinds.push("synthesized-header"),{text:[...lines.slice(0,firstSalvageableIndex),CANDIDATE_HEADERS[fallbackFamily],...lines.slice(firstSalvageableIndex)].join(`
178
178
  `),synthesizedHeader:!0,repairKinds}}function candidateArtifactCacheKey(rawText,fallbackFamily){return createHash2("sha256").update(`${rawText}\x00${fallbackFamily}`).digest("hex")}function normalizeCandidateArtifactCached(rawText,fallbackFamily){let key=candidateArtifactCacheKey(rawText,fallbackFamily),hit=candidateArtifactCache.get(key);if(hit!==void 0)return candidateArtifactCacheHits++,hit;candidateArtifactCacheMisses++;let result=normalizeCandidateArtifact(rawText,fallbackFamily);if(candidateArtifactCache.size>=CANDIDATE_ARTIFACT_CACHE_CAPACITY){let oldest=candidateArtifactCache.keys().next().value;if(oldest!==void 0)candidateArtifactCache.delete(oldest)}return candidateArtifactCache.set(key,result),result}function analyzeCandidateLaneContext(context){let issues=[],baseBound=Boolean(context.expected_lane||context.expected_lanes),microBound=Boolean(context.expected_micro_lane||context.expected_micro_lanes);if(context.expected_lanes){if(!context.expected_lane)issues.push({field:"expected_lane",message:"expected_lane is required when expected_lanes is supplied"});if(new Set(context.expected_lanes).size!==context.expected_lanes.length)issues.push({field:"expected_lanes",message:"expected_lanes must contain unique lane identities"});if(context.expected_lane&&!context.expected_lanes.includes(context.expected_lane))issues.push({field:"expected_lanes",message:"expected_lanes must contain expected_lane"})}if(context.expected_micro_lanes){if(!context.expected_micro_lane)issues.push({field:"expected_micro_lane",message:"expected_micro_lane is required when expected_micro_lanes is supplied"});if(new Set(context.expected_micro_lanes).size!==context.expected_micro_lanes.length)issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain unique lane identities"});if(context.expected_micro_lane&&!context.expected_micro_lanes.includes(context.expected_micro_lane))issues.push({field:"expected_micro_lanes",message:"expected_micro_lanes must contain expected_micro_lane"})}if(!context.expected_family&&baseBound&&microBound)issues.push({field:"expected_family",message:"base and micro ownership fields cannot be combined without one expected_family"});else if(context.expected_family==="base_explorer"&&microBound)issues.push({field:"expected_family",message:"base_explorer ownership cannot include expected_micro_lane fields"});else if(context.expected_family==="micro_lane"&&baseBound)issues.push({field:"expected_family",message:"micro_lane ownership cannot include expected_lane fields"});else if(!context.expected_family&&baseBound)issues.push({field:"expected_family",message:"base ownership fields require expected_family base_explorer"});else if(!context.expected_family&&microBound)issues.push({field:"expected_family",message:"micro ownership fields require expected_family micro_lane"});return issues}function splitPipeFields(line){let fields=[],current="";for(let index=0;index<line.length;index++){let char=line[index];if(char==="\\"&&index+1<line.length&&line[index+1]==="|"){current+="|",index++;continue}if(char==="|"){fields.push(current),current="";continue}current+=char}return fields.push(current),fields}function candidateDiagnosticPreview(value){let normalized=value.replace(/[\r\n\t]+/g," ").trim();if(normalized.length<=CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)return normalized;return`${normalized.slice(0,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS)}...`}function isCandidateSeverity(value){return value!==null&&value!==void 0&&CANDIDATE_SEVERITIES.includes(value)}function isCandidateConfidence(value){return value!==null&&value!==void 0&&CANDIDATE_CONFIDENCES.includes(value)}function isCandidateLookingShortRow(fields,_context,explicitCandidateMarker=!1){if(explicitCandidateMarker||fields[0]?.trim()==="[CANDIDATE]")return!0;return fields.length>=2}function analyzeCandidateFields(fields,family){let names=CANDIDATE_FIELDS[family],trimmed=fields.map((field)=>field.trim()),values={},issues=[];if(trimmed.length!==CANDIDATE_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CANDIDATE_FIELD_COUNT} candidate fields, received ${trimmed.length}`});for(let index=0;index<names.length;index++){let name=names[index],value=trimmed[index]?.trim()||null;if(values[name]=value,value===null&&name!=="risk_impact"&&name!=="risk_tags")issues.push({field:name,message:`Missing required field: ${name}`})}let severity=values.severity;if(severity!==null&&!isCandidateSeverity(severity))issues.push({field:"severity",message:`Invalid severity: ${candidateDiagnosticPreview(severity)}; expected ${CANDIDATE_SEVERITIES.join("|")}`});let confidence=values.confidence;if(confidence!==null&&!isCandidateConfidence(confidence))issues.push({field:"confidence",message:`Invalid confidence: ${candidateDiagnosticPreview(confidence)}; expected ${CANDIDATE_CONFIDENCES.join("|")}`});let riskImpact=values.risk_impact;if(riskImpact!==null&&!PR_REVIEW_RISK_IMPACTS.includes(riskImpact))issues.push({field:"risk_impact",message:`Invalid risk_impact: ${candidateDiagnosticPreview(riskImpact)}; expected ${PR_REVIEW_RISK_IMPACTS.join("|")}`});let riskTags=values.risk_tags;if(riskTags!==null){let parsedTags=parsePrReviewRiskTagsField(riskTags),known=new Set(PR_REVIEW_RISK_TAGS);if(riskTags!==""&&(parsedTags.length===0||parsedTags.some((tag)=>!known.has(tag))))issues.push({field:"risk_tags",message:`Invalid risk_tags: ${candidateDiagnosticPreview(riskTags)}; expected a comma-separated subset of ${PR_REVIEW_RISK_TAGS.join("|")}, or empty`})}return{valid:issues.length===0,issues,values,candidateId:values.candidate_id,workflowLane:family==="base_explorer"?values.lane:values.micro_lane}}function analyzeCleanFields(fields,family,expectedLane){let trimmed=fields.map((field)=>field.trim()),issues=[],laneField=family==="base_explorer"?"lane":"micro_lane";if(trimmed.length!==CLEAN_FIELD_COUNT)issues.push({field:"row",message:`Expected exactly ${CLEAN_FIELD_COUNT-1} CLEAN fields after [CLEAN], received ${Math.max(0,trimmed.length-1)}`});if(trimmed[0]!=="[CLEAN]")issues.push({field:"row",message:"CLEAN row must begin with [CLEAN]"});let lane=trimmed[1]||null,coverageScope=trimmed[2]||null,evidence=trimmed[3]||null;if(lane===null)issues.push({field:laneField,message:`Missing required field: ${laneField}`});else if(expectedLane!==void 0&&lane!==expectedLane)issues.push({field:laneField,message:`Expected ${laneField} ${candidateDiagnosticPreview(expectedLane)}, received ${candidateDiagnosticPreview(lane)}`});if(coverageScope===null)issues.push({field:"coverage_scope",message:"Missing required field: coverage_scope"});else if(coverageScope.length<CLEAN_COVERAGE_SCOPE_MIN_CHARS)issues.push({field:"coverage_scope",message:`coverage_scope must contain at least ${CLEAN_COVERAGE_SCOPE_MIN_CHARS} characters`});if(evidence===null)issues.push({field:"evidence",message:"Missing required field: evidence"});else if(evidence.length<CLEAN_EVIDENCE_MIN_CHARS)issues.push({field:"evidence",message:`evidence must contain at least ${CLEAN_EVIDENCE_MIN_CHARS} characters`});return{valid:issues.length===0,issues,lane,coverageScope,evidence}}function analyzeCandidateLine(line,family){let fields=splitPipeFields(line).map((field)=>field.trim());if(fields[0]!=="[CANDIDATE]")return null;return analyzeCandidateFields(fields.slice(1),family)}var CANDIDATE_SEVERITIES,FINDINGS_SEVERITIES,CANDIDATE_CONFIDENCES,CANDIDATE_FIELD_COUNT=11,CANDIDATE_LEGACY_FIELD_COUNT=9,CLEAN_FIELD_COUNT=4,CLEAN_COVERAGE_SCOPE_MIN_CHARS=12,CLEAN_EVIDENCE_MIN_CHARS=20,CANDIDATE_DIAGNOSTIC_PREVIEW_CHARS=160,CANDIDATE_FIELDS,CANDIDATE_REQUIRED_FIELDS,CANDIDATE_MARKER="[CANDIDATE]",CLEAN_MARKER="[CLEAN]",CANDIDATE_HEADERS,CLEAN_TEMPLATES,NON_CONTRACT_MARKER_LINE,CANDIDATE_ARTIFACT_CACHE_CAPACITY=512,candidateArtifactCache,candidateArtifactCacheHits=0,candidateArtifactCacheMisses=0;var init_candidate_contract=__esm(()=>{init_pr_review_contract();init_pr_review_contract();CANDIDATE_SEVERITIES=["INFO","LOW","MEDIUM","HIGH","CRITICAL"],FINDINGS_SEVERITIES=[...CANDIDATE_SEVERITIES,"NONE"],CANDIDATE_CONFIDENCES=["HIGH","MEDIUM","LOW"],CANDIDATE_FIELDS={base_explorer:["candidate_id","lane","severity","category","file_line","claim","evidence_summary","impact_context","confidence","risk_impact","risk_tags"],micro_lane:["candidate_id","micro_lane","severity","category","file_line","claim","invariant_violated","evidence_summary","confidence","risk_impact","risk_tags"]},CANDIDATE_REQUIRED_FIELDS={base_explorer:CANDIDATE_FIELDS.base_explorer.filter((field)=>field!=="risk_impact"&&field!=="risk_tags"),micro_lane:CANDIDATE_FIELDS.micro_lane.filter((field)=>field!=="risk_impact"&&field!=="risk_tags")};CANDIDATE_HEADERS={base_explorer:formatCandidateHeader("base_explorer"),micro_lane:formatCandidateHeader("micro_lane")},CLEAN_TEMPLATES={base_explorer:formatCleanTemplate("base_explorer"),micro_lane:formatCleanTemplate("micro_lane")};NON_CONTRACT_MARKER_LINE=/^\[(?!(?:CANDIDATE|CLEAN)\])[A-Z][A-Z0-9_-]*\]/;candidateArtifactCache=new Map});var require_polyfills=__commonJS((exports,module)=>{var constants=__require("constants"),origCwd=process.cwd,cwd=null,platform=process.env.GRACEFUL_FS_PLATFORM||process.platform;process.cwd=function(){if(!cwd)cwd=origCwd.call(process);return cwd};try{process.cwd()}catch(er){}if(typeof process.chdir==="function"){if(chdir=process.chdir,process.chdir=function(d){cwd=null,chdir.call(process,d)},Object.setPrototypeOf)Object.setPrototypeOf(process.chdir,chdir)}var chdir;module.exports=patch;function patch(fs4){if(constants.hasOwnProperty("O_SYMLINK")&&process.version.match(/^v0\.6\.[0-2]|^v0\.5\./))patchLchmod(fs4);if(!fs4.lutimes)patchLutimes(fs4);if(fs4.chown=chownFix(fs4.chown),fs4.fchown=chownFix(fs4.fchown),fs4.lchown=chownFix(fs4.lchown),fs4.chmod=chmodFix(fs4.chmod),fs4.fchmod=chmodFix(fs4.fchmod),fs4.lchmod=chmodFix(fs4.lchmod),fs4.chownSync=chownFixSync(fs4.chownSync),fs4.fchownSync=chownFixSync(fs4.fchownSync),fs4.lchownSync=chownFixSync(fs4.lchownSync),fs4.chmodSync=chmodFixSync(fs4.chmodSync),fs4.fchmodSync=chmodFixSync(fs4.fchmodSync),fs4.lchmodSync=chmodFixSync(fs4.lchmodSync),fs4.stat=statFix(fs4.stat),fs4.fstat=statFix(fs4.fstat),fs4.lstat=statFix(fs4.lstat),fs4.statSync=statFixSync(fs4.statSync),fs4.fstatSync=statFixSync(fs4.fstatSync),fs4.lstatSync=statFixSync(fs4.lstatSync),fs4.chmod&&!fs4.lchmod)fs4.lchmod=function(path6,mode,cb){if(cb)process.nextTick(cb)},fs4.lchmodSync=function(){};if(fs4.chown&&!fs4.lchown)fs4.lchown=function(path6,uid,gid,cb){if(cb)process.nextTick(cb)},fs4.lchownSync=function(){};if(platform==="win32")fs4.rename=typeof fs4.rename!=="function"?fs4.rename:function(fs$rename){function rename2(from,to,cb){var start=Date.now(),backoff=0;fs$rename(from,to,function CB(er){if(er&&(er.code==="EACCES"||er.code==="EPERM"||er.code==="EBUSY")&&Date.now()-start<60000){if(setTimeout(function(){fs4.stat(to,function(stater,st){if(stater&&stater.code==="ENOENT")fs$rename(from,to,CB);else cb(er)})},backoff),backoff<100)backoff+=10;return}if(cb)cb(er)})}if(Object.setPrototypeOf)Object.setPrototypeOf(rename2,fs$rename);return rename2}(fs4.rename);fs4.read=typeof fs4.read!=="function"?fs4.read:function(fs$read){function read(fd,buffer,offset,length,position,callback_){var callback;if(callback_&&typeof callback_==="function"){var eagCounter=0;callback=function(er,_,__){if(er&&er.code==="EAGAIN"&&eagCounter<10)return eagCounter++,fs$read.call(fs4,fd,buffer,offset,length,position,callback);callback_.apply(this,arguments)}}return fs$read.call(fs4,fd,buffer,offset,length,position,callback)}if(Object.setPrototypeOf)Object.setPrototypeOf(read,fs$read);return read}(fs4.read),fs4.readSync=typeof fs4.readSync!=="function"?fs4.readSync:function(fs$readSync){return function(fd,buffer,offset,length,position){var eagCounter=0;while(!0)try{return fs$readSync.call(fs4,fd,buffer,offset,length,position)}catch(er){if(er.code==="EAGAIN"&&eagCounter<10){eagCounter++;continue}throw er}}}(fs4.readSync);function patchLchmod(fs5){fs5.lchmod=function(path6,mode,callback){fs5.open(path6,constants.O_WRONLY|constants.O_SYMLINK,mode,function(err,fd){if(err){if(callback)callback(err);return}fs5.fchmod(fd,mode,function(err2){fs5.close(fd,function(err22){if(callback)callback(err2||err22)})})})},fs5.lchmodSync=function(path6,mode){var fd=fs5.openSync(path6,constants.O_WRONLY|constants.O_SYMLINK,mode),threw=!0,ret;try{ret=fs5.fchmodSync(fd,mode),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret}}function patchLutimes(fs5){if(constants.hasOwnProperty("O_SYMLINK")&&fs5.futimes)fs5.lutimes=function(path6,at,mt,cb){fs5.open(path6,constants.O_SYMLINK,function(er,fd){if(er){if(cb)cb(er);return}fs5.futimes(fd,at,mt,function(er2){fs5.close(fd,function(er22){if(cb)cb(er2||er22)})})})},fs5.lutimesSync=function(path6,at,mt){var fd=fs5.openSync(path6,constants.O_SYMLINK),ret,threw=!0;try{ret=fs5.futimesSync(fd,at,mt),threw=!1}finally{if(threw)try{fs5.closeSync(fd)}catch(er){}else fs5.closeSync(fd)}return ret};else if(fs5.futimes)fs5.lutimes=function(_a2,_b,_c,cb){if(cb)process.nextTick(cb)},fs5.lutimesSync=function(){}}function chmodFix(orig){if(!orig)return orig;return function(target,mode,cb){return orig.call(fs4,target,mode,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chmodFixSync(orig){if(!orig)return orig;return function(target,mode){try{return orig.call(fs4,target,mode)}catch(er){if(!chownErOk(er))throw er}}}function chownFix(orig){if(!orig)return orig;return function(target,uid,gid,cb){return orig.call(fs4,target,uid,gid,function(er){if(chownErOk(er))er=null;if(cb)cb.apply(this,arguments)})}}function chownFixSync(orig){if(!orig)return orig;return function(target,uid,gid){try{return orig.call(fs4,target,uid,gid)}catch(er){if(!chownErOk(er))throw er}}}function statFix(orig){if(!orig)return orig;return function(target,options,cb){if(typeof options==="function")cb=options,options=null;function callback(er,stats2){if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}if(cb)cb.apply(this,arguments)}return options?orig.call(fs4,target,options,callback):orig.call(fs4,target,callback)}}function statFixSync(orig){if(!orig)return orig;return function(target,options){var stats2=options?orig.call(fs4,target,options):orig.call(fs4,target);if(stats2){if(stats2.uid<0)stats2.uid+=4294967296;if(stats2.gid<0)stats2.gid+=4294967296}return stats2}}function chownErOk(er){if(!er)return!0;if(er.code==="ENOSYS")return!0;var nonroot=!process.getuid||process.getuid()!==0;if(nonroot){if(er.code==="EINVAL"||er.code==="EPERM")return!0}return!1}}});var require_legacy_streams=__commonJS((exports,module)=>{var Stream=__require("stream").Stream;module.exports=legacy;function legacy(fs4){return{ReadStream,WriteStream};function ReadStream(path6,options){if(!(this instanceof ReadStream))return new ReadStream(path6,options);Stream.call(this);var self=this;this.path=path6,this.fd=null,this.readable=!0,this.paused=!1,this.flags="r",this.mode=438,this.bufferSize=65536,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.encoding)this.setEncoding(this.encoding);if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.end===void 0)this.end=1/0;else if(typeof this.end!=="number")throw TypeError("end must be a Number");if(this.start>this.end)throw Error("start must be <= end");this.pos=this.start}if(this.fd!==null){process.nextTick(function(){self._read()});return}fs4.open(this.path,this.flags,this.mode,function(err,fd){if(err){self.emit("error",err),self.readable=!1;return}self.fd=fd,self.emit("open",fd),self._read()})}function WriteStream(path6,options){if(!(this instanceof WriteStream))return new WriteStream(path6,options);Stream.call(this),this.path=path6,this.fd=null,this.writable=!0,this.flags="w",this.encoding="binary",this.mode=438,this.bytesWritten=0,options=options||{};var keys=Object.keys(options);for(var index=0,length=keys.length;index<length;index++){var key=keys[index];this[key]=options[key]}if(this.start!==void 0){if(typeof this.start!=="number")throw TypeError("start must be a Number");if(this.start<0)throw Error("start must be >= zero");this.pos=this.start}if(this.busy=!1,this._queue=[],this.fd===null)this._open=fs4.open,this._queue.push([this._open,this.path,this.flags,this.mode,void 0]),this.flush()}}});var require_clone=__commonJS((exports,module)=>{module.exports=clone2;var getPrototypeOf=Object.getPrototypeOf||function(obj){return obj.__proto__};function clone2(obj){if(obj===null||typeof obj!=="object")return obj;if(obj instanceof Object)var copy={__proto__:getPrototypeOf(obj)};else var copy=Object.create(null);return Object.getOwnPropertyNames(obj).forEach(function(key){Object.defineProperty(copy,key,Object.getOwnPropertyDescriptor(obj,key))}),copy}});var require_graceful_fs=__commonJS((exports,module)=>{var fs4=__require("fs"),polyfills=require_polyfills(),legacy=require_legacy_streams(),clone2=require_clone(),util=__require("util"),gracefulQueue,previousSymbol;if(typeof Symbol==="function"&&typeof Symbol.for==="function")gracefulQueue=Symbol.for("graceful-fs.queue"),previousSymbol=Symbol.for("graceful-fs.previous");else gracefulQueue="___graceful-fs.queue",previousSymbol="___graceful-fs.previous";function noop(){}function publishQueue(context,queue2){Object.defineProperty(context,gracefulQueue,{get:function(){return queue2}})}var debug=noop;if(util.debuglog)debug=util.debuglog("gfs4");else if(/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))debug=function(){var m=util.format.apply(util,arguments);m="GFS4: "+m.split(/\n/).join(`
179
- GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:442"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:662","src/plan/manager.ts:1988","src/plan/manager.ts:2042","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:230","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/tools/record-branch-freshness.ts:90","src/tools/record-trace-validation.ts:134","src/tools/record-merge-approval.ts:87","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1463","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1458","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2390","src/plan/manager.ts:2424"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:140","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:636","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1777"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/record-branch-freshness.ts":"registered-bespoke","src/tools/record-trace-validation.ts":"registered-bespoke","src/tools/record-merge-approval.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
179
+ GFS4: `),console.error(m)};if(!fs4[gracefulQueue]){if(queue=global[gracefulQueue]||[],publishQueue(fs4,queue),fs4.close=function(fs$close){function close(fd,cb){return fs$close.call(fs4,fd,function(err){if(!err)resetQueue();if(typeof cb==="function")cb.apply(this,arguments)})}return Object.defineProperty(close,previousSymbol,{value:fs$close}),close}(fs4.close),fs4.closeSync=function(fs$closeSync){function closeSync(fd){fs$closeSync.apply(fs4,arguments),resetQueue()}return Object.defineProperty(closeSync,previousSymbol,{value:fs$closeSync}),closeSync}(fs4.closeSync),/\bgfs4\b/i.test(process.env.NODE_DEBUG||""))process.on("exit",function(){debug(fs4[gracefulQueue]),__require("assert").equal(fs4[gracefulQueue].length,0)})}var queue;if(!global[gracefulQueue])publishQueue(global,fs4[gracefulQueue]);module.exports=patch(clone2(fs4));if(process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH&&!fs4.__patched)module.exports=patch(fs4),fs4.__patched=!0;function patch(fs5){polyfills(fs5),fs5.gracefulify=patch,fs5.createReadStream=createReadStream,fs5.createWriteStream=createWriteStream;var fs$readFile=fs5.readFile;fs5.readFile=readFile3;function readFile3(path6,options,cb){if(typeof options==="function")cb=options,options=null;return go$readFile(path6,options,cb);function go$readFile(path7,options2,cb2,startTime){return fs$readFile(path7,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readFile,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$writeFile=fs5.writeFile;fs5.writeFile=writeFile2;function writeFile2(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$writeFile(path6,data,options,cb);function go$writeFile(path7,data2,options2,cb2,startTime){return fs$writeFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$writeFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$appendFile=fs5.appendFile;if(fs$appendFile)fs5.appendFile=appendFile;function appendFile(path6,data,options,cb){if(typeof options==="function")cb=options,options=null;return go$appendFile(path6,data,options,cb);function go$appendFile(path7,data2,options2,cb2,startTime){return fs$appendFile(path7,data2,options2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$appendFile,[path7,data2,options2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$copyFile=fs5.copyFile;if(fs$copyFile)fs5.copyFile=copyFile2;function copyFile2(src,dest,flags,cb){if(typeof flags==="function")cb=flags,flags=0;return go$copyFile(src,dest,flags,cb);function go$copyFile(src2,dest2,flags2,cb2,startTime){return fs$copyFile(src2,dest2,flags2,function(err){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$copyFile,[src2,dest2,flags2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}var fs$readdir=fs5.readdir;fs5.readdir=readdir2;var noReaddirOptionVersions=/^v[0-5]\./;function readdir2(path6,options,cb){if(typeof options==="function")cb=options,options=null;var go$readdir=noReaddirOptionVersions.test(process.version)?function(path7,options2,cb2,startTime){return fs$readdir(path7,fs$readdirCallback(path7,options2,cb2,startTime))}:function(path7,options2,cb2,startTime){return fs$readdir(path7,options2,fs$readdirCallback(path7,options2,cb2,startTime))};return go$readdir(path6,options,cb);function fs$readdirCallback(path7,options2,cb2,startTime){return function(err,files){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$readdir,[path7,options2,cb2],err,startTime||Date.now(),Date.now()]);else{if(files&&files.sort)files.sort();if(typeof cb2==="function")cb2.call(this,err,files)}}}}if(process.version.substr(0,4)==="v0.8"){var legStreams=legacy(fs5);ReadStream=legStreams.ReadStream,WriteStream=legStreams.WriteStream}var fs$ReadStream=fs5.ReadStream;if(fs$ReadStream)ReadStream.prototype=Object.create(fs$ReadStream.prototype),ReadStream.prototype.open=ReadStream$open;var fs$WriteStream=fs5.WriteStream;if(fs$WriteStream)WriteStream.prototype=Object.create(fs$WriteStream.prototype),WriteStream.prototype.open=WriteStream$open;Object.defineProperty(fs5,"ReadStream",{get:function(){return ReadStream},set:function(val){ReadStream=val},enumerable:!0,configurable:!0}),Object.defineProperty(fs5,"WriteStream",{get:function(){return WriteStream},set:function(val){WriteStream=val},enumerable:!0,configurable:!0});var FileReadStream=ReadStream;Object.defineProperty(fs5,"FileReadStream",{get:function(){return FileReadStream},set:function(val){FileReadStream=val},enumerable:!0,configurable:!0});var FileWriteStream=WriteStream;Object.defineProperty(fs5,"FileWriteStream",{get:function(){return FileWriteStream},set:function(val){FileWriteStream=val},enumerable:!0,configurable:!0});function ReadStream(path6,options){if(this instanceof ReadStream)return fs$ReadStream.apply(this,arguments),this;else return ReadStream.apply(Object.create(ReadStream.prototype),arguments)}function ReadStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err){if(that.autoClose)that.destroy();that.emit("error",err)}else that.fd=fd,that.emit("open",fd),that.read()})}function WriteStream(path6,options){if(this instanceof WriteStream)return fs$WriteStream.apply(this,arguments),this;else return WriteStream.apply(Object.create(WriteStream.prototype),arguments)}function WriteStream$open(){var that=this;open(that.path,that.flags,that.mode,function(err,fd){if(err)that.destroy(),that.emit("error",err);else that.fd=fd,that.emit("open",fd)})}function createReadStream(path6,options){return new fs5.ReadStream(path6,options)}function createWriteStream(path6,options){return new fs5.WriteStream(path6,options)}var fs$open=fs5.open;fs5.open=open;function open(path6,flags,mode,cb){if(typeof mode==="function")cb=mode,mode=null;return go$open(path6,flags,mode,cb);function go$open(path7,flags2,mode2,cb2,startTime){return fs$open(path7,flags2,mode2,function(err,fd){if(err&&(err.code==="EMFILE"||err.code==="ENFILE"))enqueue([go$open,[path7,flags2,mode2,cb2],err,startTime||Date.now(),Date.now()]);else if(typeof cb2==="function")cb2.apply(this,arguments)})}}return fs5}function enqueue(elem){debug("ENQUEUE",elem[0].name,elem[1]),fs4[gracefulQueue].push(elem),retry()}var retryTimer;function resetQueue(){var now=Date.now();for(var i=0;i<fs4[gracefulQueue].length;++i)if(fs4[gracefulQueue][i].length>2)fs4[gracefulQueue][i][3]=now,fs4[gracefulQueue][i][4]=now;retry()}function retry(){if(clearTimeout(retryTimer),retryTimer=void 0,fs4[gracefulQueue].length===0)return;var elem=fs4[gracefulQueue].shift(),fn2=elem[0],args2=elem[1],err=elem[2],startTime=elem[3],lastTime=elem[4];if(startTime===void 0)debug("RETRY",fn2.name,args2),fn2.apply(null,args2);else if(Date.now()-startTime>=60000){debug("TIMEOUT",fn2.name,args2);var cb=args2.pop();if(typeof cb==="function")cb.call(null,err)}else{var sinceAttempt=Date.now()-lastTime,sinceStart=Math.max(lastTime-startTime,1),desiredDelay=Math.min(sinceStart*1.2,100);if(sinceAttempt>=desiredDelay)debug("RETRY",fn2.name,args2),fn2.apply(null,args2.concat([startTime]));else fs4[gracefulQueue].push(elem)}if(retryTimer===void 0)retryTimer=setTimeout(retry,0)}});var require_retry_operation=__commonJS((exports,module)=>{function RetryOperation(timeouts,options){if(typeof options==="boolean")options={forever:options};if(this._originalTimeouts=JSON.parse(JSON.stringify(timeouts)),this._timeouts=timeouts,this._options=options||{},this._maxRetryTime=options&&options.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._options.forever)this._cachedTimeouts=this._timeouts.slice(0)}module.exports=RetryOperation;RetryOperation.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts};RetryOperation.prototype.stop=function(){if(this._timeout)clearTimeout(this._timeout);this._timeouts=[],this._cachedTimeouts=null};RetryOperation.prototype.retry=function(err){if(this._timeout)clearTimeout(this._timeout);if(!err)return!1;var currentTime=new Date().getTime();if(err&&currentTime-this._operationStart>=this._maxRetryTime)return this._errors.unshift(Error("RetryOperation timeout occurred")),!1;this._errors.push(err);var timeout=this._timeouts.shift();if(timeout===void 0)if(this._cachedTimeouts)this._errors.splice(this._errors.length-1,this._errors.length),this._timeouts=this._cachedTimeouts.slice(0),timeout=this._timeouts.shift();else return!1;var self=this,timer=setTimeout(function(){if(self._attempts++,self._operationTimeoutCb){if(self._timeout=setTimeout(function(){self._operationTimeoutCb(self._attempts)},self._operationTimeout),self._options.unref)self._timeout.unref()}self._fn(self._attempts)},timeout);if(this._options.unref)timer.unref();return!0};RetryOperation.prototype.attempt=function(fn2,timeoutOps){if(this._fn=fn2,timeoutOps){if(timeoutOps.timeout)this._operationTimeout=timeoutOps.timeout;if(timeoutOps.cb)this._operationTimeoutCb=timeoutOps.cb}var self=this;if(this._operationTimeoutCb)this._timeout=setTimeout(function(){self._operationTimeoutCb()},self._operationTimeout);this._operationStart=new Date().getTime(),this._fn(this._attempts)};RetryOperation.prototype.try=function(fn2){console.log("Using RetryOperation.try() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=function(fn2){console.log("Using RetryOperation.start() is deprecated"),this.attempt(fn2)};RetryOperation.prototype.start=RetryOperation.prototype.try;RetryOperation.prototype.errors=function(){return this._errors};RetryOperation.prototype.attempts=function(){return this._attempts};RetryOperation.prototype.mainError=function(){if(this._errors.length===0)return null;var counts={},mainError=null,mainErrorCount=0;for(var i=0;i<this._errors.length;i++){var error49=this._errors[i],message=error49.message,count=(counts[message]||0)+1;if(counts[message]=count,count>=mainErrorCount)mainError=error49,mainErrorCount=count}return mainError}});var require_retry=__commonJS((exports)=>{var RetryOperation=require_retry_operation();exports.operation=function(options){var timeouts=exports.timeouts(options);return new RetryOperation(timeouts,{forever:options&&options.forever,unref:options&&options.unref,maxRetryTime:options&&options.maxRetryTime})};exports.timeouts=function(options){if(options instanceof Array)return[].concat(options);var opts={retries:10,factor:2,minTimeout:1000,maxTimeout:1/0,randomize:!1};for(var key in options)opts[key]=options[key];if(opts.minTimeout>opts.maxTimeout)throw Error("minTimeout is greater than maxTimeout");var timeouts=[];for(var i=0;i<opts.retries;i++)timeouts.push(this.createTimeout(i,opts));if(options&&options.forever&&!timeouts.length)timeouts.push(this.createTimeout(i,opts));return timeouts.sort(function(a,b){return a-b}),timeouts};exports.createTimeout=function(attempt,opts){var random=opts.randomize?Math.random()+1:1,timeout=Math.round(random*opts.minTimeout*Math.pow(opts.factor,attempt));return timeout=Math.min(timeout,opts.maxTimeout),timeout};exports.wrap=function(obj,options,methods){if(options instanceof Array)methods=options,options=null;if(!methods){methods=[];for(var key in obj)if(typeof obj[key]==="function")methods.push(key)}for(var i=0;i<methods.length;i++){var method=methods[i],original=obj[method];obj[method]=function(original2){var op=exports.operation(options),args2=Array.prototype.slice.call(arguments,1),callback=args2.pop();args2.push(function(err){if(op.retry(err))return;if(err)arguments[0]=op.mainError();callback.apply(this,arguments)}),op.attempt(function(){original2.apply(obj,args2)})}.bind(obj,original),obj[method].options=options}}});var require_signals=__commonJS((exports,module)=>{module.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];if(process.platform!=="win32")module.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");if(process.platform==="linux")module.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var require_signal_exit=__commonJS((exports,module)=>{var process3=global.process,processOk=function(process4){return process4&&typeof process4==="object"&&typeof process4.removeListener==="function"&&typeof process4.emit==="function"&&typeof process4.reallyExit==="function"&&typeof process4.listeners==="function"&&typeof process4.kill==="function"&&typeof process4.pid==="number"&&typeof process4.on==="function"};if(!processOk(process3))module.exports=function(){return function(){}};else{if(assert2=__require("assert"),signals=require_signals(),isWin=/^win/i.test(process3.platform),EE=__require("events"),typeof EE!=="function")EE=EE.EventEmitter;if(process3.__signal_exit_emitter__)emitter=process3.__signal_exit_emitter__;else emitter=process3.__signal_exit_emitter__=new EE,emitter.count=0,emitter.emitted={};if(!emitter.infinite)emitter.setMaxListeners(1/0),emitter.infinite=!0;module.exports=function(cb,opts){if(!processOk(global.process))return function(){};if(assert2.equal(typeof cb,"function","a callback must be provided for exit handler"),loaded===!1)load();var ev="exit";if(opts&&opts.alwaysLast)ev="afterexit";var remove=function(){if(emitter.removeListener(ev,cb),emitter.listeners("exit").length===0&&emitter.listeners("afterexit").length===0)unload()};return emitter.on(ev,cb),remove},unload=function(){if(!loaded||!processOk(global.process))return;loaded=!1,signals.forEach(function(sig){try{process3.removeListener(sig,sigListeners[sig])}catch(er){}}),process3.emit=originalProcessEmit,process3.reallyExit=originalProcessReallyExit,emitter.count-=1},module.exports.unload=unload,emit=function(event,code,signal){if(emitter.emitted[event])return;emitter.emitted[event]=!0,emitter.emit(event,code,signal)},sigListeners={},signals.forEach(function(sig){sigListeners[sig]=function(){if(!processOk(global.process))return;var listeners=process3.listeners(sig);if(listeners.length===emitter.count){if(unload(),emit("exit",null,sig),emit("afterexit",null,sig),isWin&&sig==="SIGHUP")sig="SIGINT";process3.kill(process3.pid,sig)}}}),module.exports.signals=function(){return signals},loaded=!1,load=function(){if(loaded||!processOk(global.process))return;loaded=!0,emitter.count+=1,signals=signals.filter(function(sig){try{return process3.on(sig,sigListeners[sig]),!0}catch(er){return!1}}),process3.emit=processEmit,process3.reallyExit=processReallyExit},module.exports.load=load,originalProcessReallyExit=process3.reallyExit,processReallyExit=function(code){if(!processOk(global.process))return;process3.exitCode=code||0,emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),originalProcessReallyExit.call(process3,process3.exitCode)},originalProcessEmit=process3.emit,processEmit=function(ev,arg){if(ev==="exit"&&processOk(global.process)){if(arg!==void 0)process3.exitCode=arg;var ret=originalProcessEmit.apply(this,arguments);return emit("exit",process3.exitCode,null),emit("afterexit",process3.exitCode,null),ret}else return originalProcessEmit.apply(this,arguments)}}var assert2,signals,isWin,EE,emitter,unload,emit,sigListeners,loaded,load,originalProcessReallyExit,processReallyExit,originalProcessEmit,processEmit});var require_mtime_precision=__commonJS((exports,module)=>{var cacheSymbol=Symbol();function probe(file2,fs4,callback){let cachedPrecision=fs4[cacheSymbol];if(cachedPrecision)return fs4.stat(file2,(err,stat4)=>{if(err)return callback(err);callback(null,stat4.mtime,cachedPrecision)});let mtime=new Date(Math.ceil(Date.now()/1000)*1000+5);fs4.utimes(file2,mtime,mtime,(err)=>{if(err)return callback(err);fs4.stat(file2,(err2,stat4)=>{if(err2)return callback(err2);let precision=stat4.mtime.getTime()%1000===0?"s":"ms";Object.defineProperty(fs4,cacheSymbol,{value:precision}),callback(null,stat4.mtime,precision)})})}function getMtime(precision){let now=Date.now();if(precision==="s")now=Math.ceil(now/1000)*1000;return new Date(now)}exports.probe=probe;exports.getMtime=getMtime});var require_lockfile=__commonJS((exports,module)=>{var path6=__require("path"),fs4=require_graceful_fs(),retry=require_retry(),onExit=require_signal_exit(),mtimePrecision=require_mtime_precision(),locks={};function getLockFile(file2,options){return options.lockfilePath||`${file2}.lock`}function resolveCanonicalPath(file2,options,callback){if(!options.realpath)return callback(null,path6.resolve(file2));options.fs.realpath(file2,callback)}function acquireLock(file2,options,callback){let lockfilePath=getLockFile(file2,options);options.fs.mkdir(lockfilePath,(err)=>{if(!err)return mtimePrecision.probe(lockfilePath,options.fs,(err2,mtime,mtimePrecision2)=>{if(err2)return options.fs.rmdir(lockfilePath,()=>{}),callback(err2);callback(null,mtime,mtimePrecision2)});if(err.code!=="EEXIST")return callback(err);if(options.stale<=0)return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));options.fs.stat(lockfilePath,(err2,stat4)=>{if(err2){if(err2.code==="ENOENT")return acquireLock(file2,{...options,stale:0},callback);return callback(err2)}if(!isLockStale(stat4,options))return callback(Object.assign(Error("Lock file is already being held"),{code:"ELOCKED",file:file2}));removeLock(file2,options,(err3)=>{if(err3)return callback(err3);acquireLock(file2,{...options,stale:0},callback)})})})}function isLockStale(stat4,options){return stat4.mtime.getTime()<Date.now()-options.stale}function removeLock(file2,options,callback){options.fs.rmdir(getLockFile(file2,options),(err)=>{if(err&&err.code!=="ENOENT")return callback(err);callback()})}function updateLock(file2,options){let lock2=locks[file2];if(lock2.updateTimeout)return;if(lock2.updateDelay=lock2.updateDelay||options.update,lock2.updateTimeout=setTimeout(()=>{lock2.updateTimeout=null,options.fs.stat(lock2.lockfilePath,(err,stat4)=>{let isOverThreshold=lock2.lastUpdate+options.stale<Date.now();if(err){if(err.code==="ENOENT"||isOverThreshold)return setLockAsCompromised(file2,lock2,Object.assign(err,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}if(lock2.mtime.getTime()!==stat4.mtime.getTime())return setLockAsCompromised(file2,lock2,Object.assign(Error("Unable to update lock within the stale threshold"),{code:"ECOMPROMISED"}));let mtime=mtimePrecision.getMtime(lock2.mtimePrecision);options.fs.utimes(lock2.lockfilePath,mtime,mtime,(err2)=>{let isOverThreshold2=lock2.lastUpdate+options.stale<Date.now();if(lock2.released)return;if(err2){if(err2.code==="ENOENT"||isOverThreshold2)return setLockAsCompromised(file2,lock2,Object.assign(err2,{code:"ECOMPROMISED"}));return lock2.updateDelay=1000,updateLock(file2,options)}lock2.mtime=mtime,lock2.lastUpdate=Date.now(),lock2.updateDelay=null,updateLock(file2,options)})})},lock2.updateDelay),lock2.updateTimeout.unref)lock2.updateTimeout.unref()}function setLockAsCompromised(file2,lock2,err){if(lock2.released=!0,lock2.updateTimeout)clearTimeout(lock2.updateTimeout);if(locks[file2]===lock2)delete locks[file2];lock2.options.onCompromised(err)}function lock(file2,options,callback){options={stale:1e4,update:null,realpath:!0,retries:0,fs:fs4,onCompromised:(err)=>{throw err},...options},options.retries=options.retries||0,options.retries=typeof options.retries==="number"?{retries:options.retries}:options.retries,options.stale=Math.max(options.stale||0,2000),options.update=options.update==null?options.stale/2:options.update||0,options.update=Math.max(Math.min(options.update,options.stale/2),1000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let operation=retry.operation(options.retries);operation.attempt(()=>{acquireLock(file3,options,(err2,mtime,mtimePrecision2)=>{if(operation.retry(err2))return;if(err2)return callback(operation.mainError());let lock2=locks[file3]={lockfilePath:getLockFile(file3,options),mtime,mtimePrecision:mtimePrecision2,options,lastUpdate:Date.now()};updateLock(file3,options),callback(null,(releasedCallback)=>{if(lock2.released)return releasedCallback&&releasedCallback(Object.assign(Error("Lock is already released"),{code:"ERELEASED"}));unlock(file3,{...options,realpath:!1},releasedCallback)})})})})}function unlock(file2,options,callback){options={fs:fs4,realpath:!0,...options},resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);let lock2=locks[file3];if(!lock2)return callback(Object.assign(Error("Lock is not acquired/owned by you"),{code:"ENOTACQUIRED"}));lock2.updateTimeout&&clearTimeout(lock2.updateTimeout),lock2.released=!0,delete locks[file3],removeLock(file3,options,callback)})}function check2(file2,options,callback){options={stale:1e4,realpath:!0,fs:fs4,...options},options.stale=Math.max(options.stale||0,2000),resolveCanonicalPath(file2,options,(err,file3)=>{if(err)return callback(err);options.fs.stat(getLockFile(file3,options),(err2,stat4)=>{if(err2)return err2.code==="ENOENT"?callback(null,!1):callback(err2);return callback(null,!isLockStale(stat4,options))})})}function getLocks(){return locks}onExit(()=>{for(let file2 in locks){let options=locks[file2].options;try{options.fs.rmdirSync(getLockFile(file2,options))}catch(e){}}});exports.lock=lock;exports.unlock=unlock;exports.check=check2;exports.getLocks=getLocks});var require_adapter=__commonJS((exports,module)=>{var fs4=require_graceful_fs();function createSyncFs(fs5){let methods=["mkdir","realpath","stat","rmdir","utimes"],newFs={...fs5};return methods.forEach((method)=>{newFs[method]=(...args2)=>{let callback=args2.pop(),ret;try{ret=fs5[`${method}Sync`](...args2)}catch(err){return callback(err)}callback(null,ret)}}),newFs}function toPromise(method){return(...args2)=>new Promise((resolve4,reject)=>{args2.push((err,result)=>{if(err)reject(err);else resolve4(result)}),method(...args2)})}function toSync(method){return(...args2)=>{let err,result;if(args2.push((_err,_result)=>{err=_err,result=_result}),method(...args2),err)throw err;return result}}function toSyncOptions(options){if(options={...options},options.fs=createSyncFs(options.fs||fs4),typeof options.retries==="number"&&options.retries>0||options.retries&&typeof options.retries.retries==="number"&&options.retries.retries>0)throw Object.assign(Error("Cannot use retries with the sync api"),{code:"ESYNC"});return options}module.exports={toPromise,toSync,toSyncOptions}});var require_proper_lockfile=__commonJS((exports,module)=>{var lockfile=require_lockfile(),{toPromise,toSync,toSyncOptions}=require_adapter();async function lock(file2,options){let release=await toPromise(lockfile.lock)(file2,options);return toPromise(release)}function lockSync(file2,options){let release=toSync(lockfile.lock)(file2,toSyncOptions(options));return toSync(release)}function unlock(file2,options){return toPromise(lockfile.unlock)(file2,options)}function unlockSync(file2,options){return toSync(lockfile.unlock)(file2,toSyncOptions(options))}function check2(file2,options){return toPromise(lockfile.check)(file2,options)}function checkSync(file2,options){return toSync(lockfile.check)(file2,toSyncOptions(options))}module.exports=lock;module.exports.lock=lock;module.exports.unlock=unlock;module.exports.lockSync=lockSync;module.exports.unlockSync=unlockSync;module.exports.check=check2;module.exports.checkSync=checkSync});var SwarmError;var init_errors3=__esm(()=>{SwarmError=class SwarmError extends Error{code;guidance;constructor(message,code,guidance){super(message);this.name="SwarmError",this.code=code,this.guidance=guidance}}});function escapeRegex2(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function simpleGlobToRegex(pattern,flags="i"){let escaped=pattern.split("*").map((starSegment)=>starSegment.split("?").map(escapeRegex2).join(".")).join(".*");return new RegExp(`^${escaped}$`,flags)}var init_utils=__esm(()=>{init_errors3();init_logger();init_merge()});import{randomBytes}from"node:crypto";import*as fs4 from"node:fs";import*as path6 from"node:path";function matchTempGrammar(basename2){return SWARM_TEMP_GRAMMARS.find((g)=>g.match.test(basename2))}function parseTargetBasename(basename2){for(let g of SWARM_TEMP_GRAMMARS){if(!g.parsesTarget)continue;let m=g.match.exec(basename2);if(m?.[1])return m[1]}return null}function assertWellFormedTargetPath(targetPath){if(!path6.isAbsolute(targetPath))throw Error(`atomic-write target must be absolute: ${targetPath}`);if(/[\0-\x1f\x7f]/.test(targetPath))throw Error("atomic-write target contains control characters");if(/[*?]/.test(targetPath)||/(^|[/\\])\{[^}]*\}([/\\]|$)/.test(targetPath))throw Error(`atomic-write target contains glob metacharacters: ${targetPath}`);if(/(^|[/\\])~([/\\]|$)/.test(targetPath))throw Error("atomic-write target contains unresolved home-dir marker (~)");if(/\$\{?[A-Za-z_][A-Za-z0-9_]*\}?/.test(targetPath)||/%[^/\\%]+%/.test(targetPath))throw Error("atomic-write target contains unresolved environment-variable form")}function lstatNotSymlink(p,what){if(fs4.lstatSync(p).isSymbolicLink())throw Error(`${what} is a symlink/reparse point: ${p}`)}function assertSwarmContainedTarget(targetPath){assertWellFormedTargetPath(targetPath);let resolved=path6.normalize(path6.resolve(targetPath)),segments=resolved.split(path6.sep),swarmIdx=-1;for(let i=segments.length-2;i>=1;i--)if(segments[i]===".swarm"){swarmIdx=i;break}if(swarmIdx===-1)throw Error(`atomic-write target is not under a project .swarm root: ${targetPath}`);let swarmRoot=segments.slice(0,swarmIdx+1).join(path6.sep);try{let st=fs4.lstatSync(swarmRoot);if(!st.isDirectory()||st.isSymbolicLink())throw Error(`.swarm root is not a real directory (symlink/reparse or non-dir): ${swarmRoot}`)}catch(err){if(err?.code!=="ENOENT")throw err}let rel=path6.relative(swarmRoot,resolved);if(!rel||rel.startsWith("..")||path6.isAbsolute(rel))throw Error(`atomic-write target escapes .swarm root: ${targetPath}`);let probe=swarmRoot;for(let seg of rel.split(path6.sep)){if(probe=path6.join(probe,seg),!fs4.existsSync(probe))break;lstatNotSymlink(probe,"path segment under .swarm")}return{projectRoot:path6.dirname(swarmRoot),swarmRoot}}function noteRecentWriteActivity(resolvedTarget){recentWriteActivity.delete(resolvedTarget),recentWriteActivity.set(resolvedTarget,Date.now());while(recentWriteActivity.size>MAX_RECENT_WRITE_TRACKED_PATHS){let oldest=recentWriteActivity.keys().next().value;if(oldest===void 0)break;recentWriteActivity.delete(oldest)}}function clearRecentWriteActivity(targetPath){return recentWriteActivity.delete(path6.resolve(targetPath))}function wasRecentlyWrittenByThisProcess(targetPath,withinMs=RECENT_WRITE_WINDOW_MS){let last=recentWriteActivity.get(path6.resolve(targetPath));if(last===void 0)return!1;return Date.now()-last<=withinMs}function toBuffer(content){if(typeof content==="string")return Buffer.from(content,"utf-8");return content}function syncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function renameWithRetry(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=RENAME_RETRY_DELAYS_MS.length;attempt++)try{_internals8.renameSync(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES.has(code))throw err;if(attempt<RENAME_RETRY_DELAYS_MS.length)syncSleep(RENAME_RETRY_DELAYS_MS[attempt])}throw lastError}function writeAtomicSync(targetPath,content,options){if(options?.contained!==!1)assertSwarmContainedTarget(targetPath);else assertWellFormedTargetPath(targetPath);let resolvedTarget=path6.resolve(targetPath);noteRecentWriteActivity(resolvedTarget);let buffer=toBuffer(content),maxBytes=options?.maxBytes??MAX_ATOMIC_WRITE_BYTES;if(buffer.byteLength>maxBytes)throw Error(`atomic write exceeds ${maxBytes} byte bound: ${buffer.byteLength}`);let tempPath=`${resolvedTarget}.${_internals8.randomSuffix()}.tmp`;fs4.mkdirSync(path6.dirname(tempPath),{recursive:!0});try{try{let fd=fs4.openSync(tempPath,"wx",options?.mode);try{let written=0;while(written<buffer.byteLength)written+=_internals8.writeSync(fd,buffer,written,buffer.byteLength-written);if(options?.skipFsync!==!0)try{_internals8.fsyncSync(fd)}catch{}}finally{fs4.closeSync(fd)}renameWithRetry(tempPath,resolvedTarget)}finally{try{_internals8.unlinkSync(tempPath)}catch{}}}catch(error49){throw clearRecentWriteActivity(resolvedTarget),error49}try{let dirFd=fs4.openSync(path6.dirname(resolvedTarget),"r");try{fs4.fsyncSync(dirFd)}finally{fs4.closeSync(dirFd)}}catch{}invalidateCachedArtifact(resolvedTarget),noteRecentWriteActivity(resolvedTarget)}async function atomicWriteSwarmFile(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,options)}function atomicWriteSwarmFileSync(targetPath,content,options){writeAtomicSync(targetPath,content,options)}async function atomicWriteFileAnyRoot(targetPath,content,options){await new Promise((resolve5)=>setImmediate(resolve5)),writeAtomicSync(targetPath,content,{...options,contained:!1})}var UUID_RE="[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}",SWARM_TEMP_GRAMMARS,WRITER_CLASSIFICATION,MAX_ATOMIC_WRITE_BYTES=268435456,RENAME_RETRY_DELAYS_MS,RETRYABLE_RENAME_CODES,MAX_RECENT_WRITE_TRACKED_PATHS=256,RECENT_WRITE_WINDOW_MS=500,recentWriteActivity,_internals8;var init_atomic_write=__esm(()=>{init_swarm_artifact_cache();SWARM_TEMP_GRAMMARS=[{id:"canonical-v1",era:"canonical",match:/^(.+)\.[0-9a-f]{32}\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/utils/atomic-write.ts:atomicWriteSwarmFile","src/utils/atomic-write.ts:atomicWriteFileAnyRoot"]},{id:"target-suffix-tmp-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/commands/handoff.ts (pre-#2035; site=handoff.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/commands/handoff.ts (pre-#2035; site=handoff-prompt.md; migrated-to=src/commands/handoff.ts:handleHandoffCommand)","src/memory/local-jsonl-provider.ts:1288","src/config/bundled-skills.ts:259"]},{id:"target-suffix-tmp-pid-uuid",era:"current",match:new RegExp(`^(.+)\\.tmp\\.\\d+\\.${UUID_RE}$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/pr-workflow-gate.ts (pre-#2385; migrated-to=src/pr-review/persistence.ts:writeAtomicJson)"],note:"pre/post-rename file-identity verification (assertOpened/ClosedSwarmFileIdentity, pr-workflow-gate.ts:17880-17980) is writer-specific and load-bearing"},{id:"target-suffix-tmp-num-num-json",era:"current",match:/^(.+)\.tmp\.\d+\.\d+\.json$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/issue-trace-state.ts:442"],note:"the .json terminator keeps this shape distinct from the bare two-token family — declared before it so first-match wins"},{id:"target-suffix-tmp-num-alnum",era:"current",match:/^(.+)\.tmp\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/evidence/task-file.ts (pre-#2035; migrated-to=src/evidence/task-file.ts:atomicWriteFile)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWrite)","src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)","src/plan/manager.ts:662","src/plan/manager.ts:1988","src/plan/manager.ts:2042","src/review/evidence.ts:175","src/turbo/lean/evidence.ts:182","src/summaries/manager.ts:163","src/evidence/manager.ts:288","src/evidence/manager.ts:456","src/tools/sast-baseline.ts:199","src/tools/repo-graph/storage.ts:543","src/memory/reflection-service.ts (pre-#2035; migrated-to=src/memory/reflection-service.ts:atomicWrite)","src/hooks/review-receipt.ts:609","src/hooks/review-receipt.ts:675","src/hooks/review-receipt.ts:894","src/knowledge/identity.ts:230","src/evidence/phase-participation.ts (pre-#2035; migrated-to=src/evidence/phase-participation.ts:atomicWriteBytes)","src/turbo/lean/integration.ts:428","src/tools/record-branch-freshness.ts:90","src/tools/record-trace-validation.ts:134","src/tools/record-merge-approval.ts:87","src/turbo/lean/reviewer.ts:403","src/plan/ledger.ts:1463","src/services/synonym-map.ts:389","src/services/skill-optimizer/store.ts:340","src/services/skill-optimizer/store.ts:503","src/turbo/epic/calibration.ts:234","src/commands/archive-sqlite.ts:318","src/memory/jsonl-migration.ts:161"],note:"fsync-discipline / lock-scoped fd writers whose temp naming is pinned by their own durability test suites (plan-durability invariant 5, #2034 crash matrix); grammars registered here so their residue stays discoverable"},{id:"target-suffix-tmp-token",era:"current",match:/^(.+)\.tmp\.[0-9a-z-]{6,}$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/turbo/lean/state.ts:129","src/turbo/lean/recovery.ts:175","src/hooks/delegation-gate/worktree-merge-status.ts:110","src/plan/ledger.ts:606"]},{id:"target-suffix-tmp-dash",era:"current",match:/^(.+)\.tmp-\d+-[0-9a-z-]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-evaluator.ts (pre-#2035; migrated-to=src/services/skill-evaluator.ts:atomicWrite)","src/services/skill-improver.ts (pre-#2035; migrated-to=src/services/skill-improver.ts:atomicWrite)","src/services/skill-consolidation.ts (pre-#2035; migrated-to=src/services/skill-consolidation.ts:atomicWrite)","src/services/skill-generator.ts (pre-#2035; migrated-to=src/services/skill-generator.ts:atomicWrite)","src/tools/spec-write.ts:98","src/sdd/effective-spec.ts:1377","src/background/lane-output-store.ts:353","src/background/pending-delegations.ts:1501","src/background/delegation-health.ts:391","src/tools/submit-phase-council-verdicts.ts:458","src/summaries/store.ts (pre-#2035; migrated-to=src/summaries/store.ts:writeRawSidecar)","src/retention/jsonl-cap.ts:213","src/services/skill-changelog.ts:58","src/turbo/epic/divergence-recorder.ts:108"],note:"background lane/delegation stores keep bounded-retry rename semantics wired into their callers (#2034/#2276 delivery contracts); migration candidates for a follow-up but grammars registered"},{id:"target-suffix-tmp-dash-num",era:"current",match:/^(.+)\.tmp-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/services/skill-improver-quota.ts:114"]},{id:"target-dot-pid-uuid-tmp",era:"current",match:new RegExp(`^(.+)\\.\\d+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/hooks/knowledge-receipt-ledger-storage.ts:591"],note:"pre/post-rename file-identity verification (existingFileIdentity checks, knowledge-receipt-ledger-storage.ts:544-591) is writer-specific and load-bearing"},{id:"dot-numeric-instance-tmp",era:"current",match:/^\..+(?:\.\d+){2,4}\.[0-9a-z]+\.tmp$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/utils/bun-compat.ts:138","src/tools/repo-graph/freshness.ts:171"],note:"bunWrite Node-fallback internal temp and the repo-graph fingerprint temp (2-4 numeric token groups); leading-dot temps are standalone, target not parsed"},{id:"dot-uuid-instance-tmp",era:"current",match:new RegExp(`^\\..+\\.${UUID_RE}\\.tmp$`),token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/tools/write-pr-review-artifact.ts:154","src/tools/write-pr-review-artifact.ts:174","src/tools/write-pr-review-trigger-eval.ts:96"],note:"bundled-skills writes outside .swarm (project skill roots) and keeps its own contained-directory logic (invariant 4 bundled-skill ownership)"},{id:"tmp-prefix-named",era:"legacy",match:/^\.tmp-.+-\d+-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!1,producers:["src/commands/issue.ts (pre-#2035; migrated-to=src/commands/issue.ts:atomicWriteFileSync)"],note:"prefix form embeds the filename; target not reliably parseable (dashes), so eligibility relies on the age/tracked/symlink/lock gates"},{id:"target-rebuild-close",era:"current",match:/^(.+)\.(?:rebuild|close)\.\d+\.[0-9a-z]+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/plan/manager.ts:2390","src/plan/manager.ts:2424"],note:"plan-durability (invariant 5) fd-write paths; grammars registered, writers unchanged in this PR"},{id:"target-migration-pid",era:"current",match:/^(.+)\.migration-\d+$/,token:"instance",quarantineEligible:!0,parsesTarget:!0,producers:["src/scope/scope-persistence.ts (pre-#2035; migrated-to=src/scope/scope-persistence.ts:atomicWriteSync)"]},{id:"dot-tmp-prefix-legacy",era:"legacy",match:/^\.tmp\..+$/,token:"constant",quarantineEligible:!0,parsesTarget:!1,producers:["pre-7.x writers (pre-#2035; scanner=src/services/swarm-residue.ts:collectCandidates)"],note:"legacy prefix grammar: issue #2035 req 7 preserves its handling — stale instances are quarantined (formerly unlinked) under the same eligibility gates"},{id:"dot-constant-tmp",era:"current",match:/^\..+\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/write-drift-evidence.ts:275","src/tools/write-mutation-evidence.ts:169","src/tools/write-hallucination-evidence.ts:121","src/tools/record-implementation-review.ts:87","src/tools/record-recurrence-sweep.ts:140","src/tools/record-issue-reproduction.ts:85","src/tools/record-issue-publication.ts:74","src/tools/write-final-council-evidence.ts:403"],note:"constant-name temps: no per-invocation token — reported when stale, never auto-quarantined (may be an in-flight writer of any process)"},{id:"target-constant-tmp",era:"current",match:/^(.+)\.tmp$/,token:"constant",quarantineEligible:!1,parsesTarget:!1,producers:["src/tools/checkpoint.ts:195","src/full-auto/state.ts:636","src/context-map/persistence.ts:119","src/context-map/capsule-persistence.ts:111","src/test-impact/history-store.ts:297","src/test-impact/history-store.ts:302","src/test-impact/history-store.ts:429","src/test-impact/history-store.ts:435","src/hooks/promotion-evidence-store.ts:112","src/hooks/skill-usage-log.ts:1165","src/hooks/skill-usage-log.ts:1675","src/hooks/skill-usage-pending.ts:817","src/parallel/file-locks.ts:113","src/plan/ledger.ts:607","src/plan/ledger.ts:1777"],note:"constant-name temps: reported when stale, never auto-quarantined. file-locks meta sidecars live under the scanner-skipped .swarm/locks/ subtree; the ledger reconcile temp embeds instance tokens but its .tmp-suffix shape maps here (conservatively report-only)"}];WRITER_CLASSIFICATION=Object.freeze({"src/commands/close.ts":"migrated","src/commands/close/context.ts":"reader-only","src/commands/close/clean-stage.ts":"reader-only","src/commands/handoff.ts":"migrated","src/commands/simulate.ts":"migrated","src/commands/coupling.ts":"migrated","src/commands/issue.ts":"migrated","src/evidence/task-file.ts":"migrated","src/evidence/phase-participation.ts":"migrated","src/memory/reflection-service.ts":"migrated","src/scope/scope-persistence.ts":"migrated","src/services/skill-consolidation.ts":"migrated","src/services/skill-evaluator.ts":"migrated","src/services/skill-generator.ts":"migrated","src/services/skill-improver.ts":"migrated","src/summaries/store.ts":"migrated","src/prm/trajectory-store.ts":"migrated","src/observability/otlp-exporter.ts":"registered-bespoke","src/retention/jsonl-cap.ts":"registered-bespoke","src/services/skill-changelog.ts":"registered-bespoke","src/turbo/epic/divergence-recorder.ts":"registered-bespoke","src/background/delegation-health.ts":"registered-bespoke","src/background/lane-output-store.ts":"registered-bespoke","src/background/pending-delegations.ts":"registered-bespoke","src/commands/archive-sqlite.ts":"registered-bespoke","src/context-map/capsule-persistence.ts":"registered-bespoke","src/context-map/persistence.ts":"registered-bespoke","src/context-map/telemetry.ts":"registered-bespoke","src/events/core-events.ts":"registered-bespoke","src/hooks/guardrails/shell-audit-store.ts":"registered-bespoke","src/evidence/documents-retention.ts":"registered-bespoke","src/evidence/manager.ts":"registered-bespoke","src/full-auto/state.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-merge-status.ts":"registered-bespoke","src/hooks/delegation-gate/worktree-provisioning-owner.ts":"migrated","src/hooks/issue-trace-state.ts":"registered-bespoke","src/hooks/knowledge-receipt-ledger-storage.ts":"registered-bespoke","src/hooks/pr-workflow-gate.ts":"registered-bespoke","src/pr-review/authorization.ts":"registered-bespoke","src/pr-review/persistence.ts":"registered-bespoke","src/hooks/promotion-evidence-store.ts":"registered-bespoke","src/hooks/review-receipt.ts":"registered-bespoke","src/hooks/skill-usage-log.ts":"registered-bespoke","src/hooks/skill-usage-pending.ts":"registered-bespoke","src/knowledge/identity.ts":"registered-bespoke","src/memory/jsonl-migration.ts":"external","src/memory/local-jsonl-provider.ts":"registered-bespoke","src/plan/ledger.ts":"registered-bespoke","src/plan/manager.ts":"registered-bespoke","src/review/evidence.ts":"registered-bespoke","src/sdd/effective-spec.ts":"registered-bespoke","src/services/skill-improver-quota.ts":"registered-bespoke","src/services/skill-optimizer/activation.ts":"external","src/services/skill-optimizer/store.ts":"registered-bespoke","src/services/skill-reviser.ts":"external","src/services/synonym-map.ts":"registered-bespoke","src/session/snapshot-writer.ts":"registered-bespoke","src/summaries/manager.ts":"registered-bespoke","src/test-impact/history-store.ts":"registered-bespoke","src/turbo/epic/calibration.ts":"registered-bespoke","src/turbo/epic/state.ts":"registered-bespoke","src/turbo/lean/evidence.ts":"registered-bespoke","src/turbo/lean/integration.ts":"registered-bespoke","src/turbo/lean/recovery.ts":"registered-bespoke","src/turbo/lean/reviewer.ts":"registered-bespoke","src/turbo/lean/state.ts":"registered-bespoke","src/tools/apply-patch.ts":"external","src/tools/checkpoint.ts":"registered-bespoke","src/tools/record-implementation-review.ts":"registered-bespoke","src/tools/record-issue-publication.ts":"registered-bespoke","src/tools/record-issue-reproduction.ts":"registered-bespoke","src/tools/record-recurrence-sweep.ts":"registered-bespoke","src/tools/record-branch-freshness.ts":"registered-bespoke","src/tools/record-trace-validation.ts":"registered-bespoke","src/tools/record-merge-approval.ts":"registered-bespoke","src/tools/repo-graph/freshness.ts":"registered-bespoke","src/tools/repo-graph/storage.ts":"registered-bespoke","src/tools/sast-baseline.ts":"registered-bespoke","src/tools/spec-write.ts":"registered-bespoke","src/tools/submit-phase-council-verdicts.ts":"registered-bespoke","src/tools/write-drift-evidence.ts":"registered-bespoke","src/tools/write-final-council-evidence.ts":"registered-bespoke","src/tools/write-hallucination-evidence.ts":"registered-bespoke","src/tools/write-mutation-evidence.ts":"registered-bespoke","src/tools/write-pr-review-artifact.ts":"registered-bespoke","src/tools/write-pr-review-trigger-eval.ts":"registered-bespoke","src/config/bundled-skills.ts":"external","src/services/config-doctor.ts":"external","src/parallel/file-locks.ts":"registered-bespoke","src/utils/bun-compat.ts":"registered-bespoke","src/background/plan-sync-worker.ts":"reader-only","src/config/lane-permissions.ts":"reader-only","src/environment/profile.ts":"reader-only","src/worktree/core.ts":"reader-only"});RENAME_RETRY_DELAYS_MS=[10,25,50,100,200],RETRYABLE_RENAME_CODES=new Set(["EPERM","EBUSY","EACCES","EEXIST"]),recentWriteActivity=new Map;_internals8={randomSuffix:()=>randomBytes(16).toString("hex"),writeSync:(fd,buffer,offset,length)=>fs4.writeSync(fd,buffer,offset,length),renameSync:(from,to)=>fs4.renameSync(from,to),unlinkSync:(p)=>fs4.unlinkSync(p),fsyncSync:(fd)=>fs4.fsyncSync(fd)}});import{spawn as nodeSpawn,spawnSync as nodeSpawnSync}from"node:child_process";import*as fsSync3 from"node:fs";import*as fsPromises2 from"node:fs/promises";import*as path7 from"node:path";function getBun(){return globalThis.Bun}function bunFile(filePath){let bun=getBun();if(bun?.file)return bun.file(filePath);let cachedSize;return{async text(){return fsPromises2.readFile(filePath,"utf-8")},async arrayBuffer(){let buf=await fsPromises2.readFile(filePath),ab=new ArrayBuffer(buf.byteLength);return new Uint8Array(ab).set(buf),ab},async exists(){try{return await fsPromises2.access(filePath,fsSync3.constants.F_OK),!0}catch{return!1}},get size(){if(cachedSize!==void 0)return cachedSize;try{cachedSize=fsSync3.statSync(filePath).size}catch{cachedSize=0}return cachedSize}}}async function bunWrite(filePath,data){let bun=getBun();if(bun?.write)return bun.write(filePath,data);let dir=path7.dirname(filePath),tempName=`.${path7.basename(filePath)}.${process.pid}.${Date.now()}.${tempCounter++}.${Math.random().toString(36).slice(2,10)}.tmp`,tempPath=path7.join(dir,tempName),buffer;if(typeof data==="string")buffer=data;else if(data instanceof ArrayBuffer)buffer=new Uint8Array(data);else if(ArrayBuffer.isView(data))buffer=new Uint8Array(data.buffer,data.byteOffset,data.byteLength);else buffer=new Uint8Array(0);try{await fsPromises2.mkdir(dir,{recursive:!0})}catch{}await fsPromises2.writeFile(tempPath,buffer);let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES;attempt++)try{await fsPromises2.rename(tempPath,filePath),lastError=void 0;break}catch(err){lastError=err;let code=err.code;if(code!=="EEXIST"&&code!=="EBUSY"&&code!=="EPERM")break;await new Promise((r)=>setTimeout(r,WINDOWS_RENAME_RETRY_DELAY_MS))}if(lastError){try{await fsPromises2.unlink(tempPath)}catch{}throw lastError}try{let dirFd=await fsPromises2.open(dir,"r");try{await dirFd.sync()}finally{await dirFd.close()}}catch{}return(await fsPromises2.stat(filePath)).size}function sleep(ms){let bun=getBun();if(bun?.sleep)return bun.sleep(ms);return new Promise((resolve5)=>setTimeout(resolve5,ms))}function collectGarbageBestEffort(){let bun=getBun();try{bun?.gc?.(!0)}catch{}}function bunHash(input){let bun=getBun();if(bun?.hash){let r=bun.hash(input);return typeof r==="bigint"?r:BigInt(r)}let bytes;if(typeof input==="string")bytes=new TextEncoder().encode(input);else if(input instanceof ArrayBuffer)bytes=new Uint8Array(input);else bytes=new Uint8Array(input.buffer,input.byteOffset,input.byteLength);let hash2=5381n;for(let b of bytes)hash2=hash2*33n+BigInt(b)&0xffffffffffffffffn;return hash2}async function killProcessTreeImpl(pid,signal,directKill,wasDetached){if(typeof pid!=="number"||pid<=0){directKill(signal);return}if(_internals9.platform()==="win32"){let taskkill;try{if(taskkill=_internals9.spawnTaskkill(["/PID",String(pid),"/T","/F"],{cwd:_internals9.cwd(),stdio:["ignore","ignore","ignore"],timeout:5000,killSignal:"SIGKILL",windowsHide:!0}),await new Promise((resolve5)=>{let settled=!1,finish=(value)=>{if(settled)return;settled=!0,resolve5(value)};taskkill?.once("error",()=>finish(!1)),taskkill?.once("exit",(code)=>finish(code===0))}))return}catch{}finally{try{taskkill?.kill("SIGKILL")}catch{}}throw directKill(signal),Error("Windows process-tree termination could not be confirmed")}if(wasDetached)try{process.kill(-pid,signal??"SIGKILL");return}catch{}directKill(signal)}function createProcessTreeKiller(pid,directKill,wasDetached){return(signal)=>killProcessTreeImpl(pid,signal,directKill,wasDetached)}function inspectSpawnCwd(cwd){try{return _internals9.statSync(cwd).isDirectory()?"directory":"not-directory"}catch(err){let code=typeof err==="object"&&err!==null&&"code"in err?err.code:void 0;if(code==="ENOENT"||code==="ENOTDIR")return"missing";if(code==="EACCES"||code==="EPERM")return"unreadable";return"unknown"}}function describeSpawnCwdFailure(cwd,executable,cause){let state2=inspectSpawnCwd(cwd);if(state2==="missing")return new SpawnCwdMissingError(cwd,"missing",executable,{cause});if(state2==="not-directory")return new SpawnCwdMissingError(cwd,"not-directory",executable,{cause});return null}function spawnErrorCode(err){if(typeof err!=="object"||err===null||!("code"in err))return;let code=err.code;return typeof code==="string"?code:void 0}function classifySpawnFailure(err,cwd){if(err instanceof SpawnCwdMissingError)return"cwd-missing";let code=spawnErrorCode(err);if(code===void 0||!AMBIGUOUS_SPAWN_CODES.has(code))return"other";if(cwd===void 0||cwd==="")return code==="ENOENT"?"binary-missing":"other";switch(inspectSpawnCwd(cwd)){case"missing":case"not-directory":return"cwd-missing";case"unreadable":case"unknown":return"cwd-unreadable";default:return code==="ENOENT"?"binary-missing":"other"}}function wrapSpawnFailure(error49,cwd,executable){let err=asError(error49);if(err instanceof SpawnCwdMissingError)return err;if(cwd===void 0||cwd==="")return err;if(classifySpawnFailure(err,cwd)!=="cwd-missing")return err;return describeSpawnCwdFailure(cwd,executable,err)??err}function normalizedMaxBuffer(value){return typeof value==="number"&&Number.isSafeInteger(value)&&value>0?value:DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES}function createOutputOverflowController(limit,requestKill){let error49,killRequested=!1,resolveCompleted,completed=new Promise((resolve5)=>{resolveCompleted=resolve5});return{get error(){return error49},completed,overflow(captured,total){if(error49)return;if(error49=new BunCompatOutputLimitError(limit,captured,total),killRequested)return;killRequested=!0;try{requestKill()}catch{}},complete(){resolveCompleted()}}}function streamFromNode(pipe2,limit,controller){if(!pipe2)return staticStream("");let mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));if(mode="buffered",collected)return collected;return collected=new Promise((resolve5)=>{if(!pipe2){resolve5(Buffer.alloc(0));return}let chunks=[],captured=0,total=0,finished=!1,finish=()=>{if(finished)return;finished=!0,resolve5(Buffer.concat(chunks))};pipe2.on("data",(chunk)=>{let bytes=typeof chunk==="string"?Buffer.from(chunk):chunk;if(total+=bytes.byteLength,controller?.error||limit===void 0)return;let remaining=limit-captured;if(remaining>0){let retained=Buffer.from(bytes.subarray(0,remaining));chunks.push(retained),captured+=retained.byteLength}if(bytes.byteLength>remaining)controller?.overflow(captured,total)}),pipe2.on("end",finish),pipe2.on("close",finish),pipe2.on("error",finish)}).then(async(bytes)=>{if(await controller?.completed,controller?.error)throw controller.error;return bytes}),collected},toWebReadable=()=>{if(!pipe2)return new ReadableStream({start(controller2){controller2.close()}});let r=pipe2;if(typeof r.toWeb==="function")return r.toWeb();return new ReadableStream({start(controller2){pipe2.on("data",(chunk)=>{controller2.enqueue(typeof chunk==="string"?new TextEncoder().encode(chunk):new Uint8Array(chunk.buffer,chunk.byteOffset,chunk.byteLength))}),pipe2.on("end",()=>controller2.close()),pipe2.on("error",(err)=>controller2.error(err))},cancel(){let destroyable=pipe2;if(typeof destroyable.destroy==="function")try{destroyable.destroy()}catch{}}})},result={async text(){return(await collect()).toString("utf-8")},async bytes(){let b=await collect();return new Uint8Array(b.buffer,b.byteOffset,b.byteLength)},getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",toWebReadable().getReader()}};if(pipe2&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mapStdio(v){return v??"pipe"}function streamFromBun(stream,limit,controller){if(!stream||typeof stream!=="object")return{async text(){return""},async bytes(){return new Uint8Array(0)},getReader(){return new ReadableStream({start(controller2){controller2.close()}}).getReader()}};let candidate=stream,mode,collected,collect=()=>{if(mode==="reader")return Promise.reject(TypeError("Subprocess output is already consumed by a reader"));return mode="buffered",collected??=(async()=>{if(typeof candidate.getReader!=="function")return new Uint8Array(0);let reader=candidate.getReader(),chunks=[],captured=0,total=0;try{for(;;){let{done,value}=await reader.read();if(done)break;if(!value)continue;if(total+=value.byteLength,controller?.error||limit===void 0)continue;let remaining=limit-captured;if(remaining>0){let retained=value.slice(0,remaining);chunks.push(retained),captured+=retained.byteLength}if(value.byteLength>remaining)controller?.overflow(captured,total)}}finally{reader.releaseLock()}if(await controller?.completed,controller?.error)throw controller.error;let out=new Uint8Array(captured),offset=0;for(let chunk of chunks)out.set(chunk,offset),offset+=chunk.byteLength;return out})(),collected},result={async text(){return new TextDecoder().decode(await collect())},bytes:collect,getReader(){if(mode!==void 0)throw TypeError("Subprocess output is already consumed");return mode="reader",typeof candidate.getReader==="function"?candidate.getReader():new ReadableStream({start(streamController){streamController.close()}}).getReader()}};if(typeof candidate.getReader==="function"&&controller&&limit!==void 0)queueMicrotask(()=>{if(mode===void 0)collect().catch(()=>{return})});return result}function mergeEnvForChild(baseEnv,envOverrides){let hasExplicitBaseEnv=baseEnv!==void 0,baseSource=baseEnv??process.env,merged={};for(let[key,value]of Object.entries(baseSource))if(typeof value==="string")merged[key]=value;if(envOverrides)for(let[key,value]of Object.entries(envOverrides))if(value===null)delete merged[key];else merged[key]=value;if(Object.keys(merged).length===0)return hasExplicitBaseEnv?{}:void 0;return merged}function asError(value){return value instanceof Error?value:Error(String(value))}function staticStream(text){let bytes=new TextEncoder().encode(text);return{async text(){return text},async bytes(){return bytes},getReader(){return new ReadableStream({start(controller){if(bytes.byteLength>0)controller.enqueue(bytes);controller.close()}}).getReader()}}}function spawnCreationFailure(error49){return{stdout:streamFromBun(void 0),stderr:staticStream(error49.message),exited:Promise.resolve(SPAWN_CREATION_FAILURE_EXIT_CODE),exitCode:null,signalCode:null,spawnError:error49,kill(){},killTree:()=>Promise.resolve()}}function bunSpawn(cmd,options){let maxBuffer=normalizedMaxBuffer(options?.maxBuffer),bun=getBun();if(bun?.spawn){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.killProcessTree,delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;if(options?.timeout&&options.timeout>0&&options.killProcessTree!==!0)spawnOpts.killSignal="SIGKILL";if(options?.killProcessTree===!0)delete spawnOpts.timeout,delete spawnOpts.killSignal,spawnOpts.detached=!0;let spawned;try{spawned=bun.spawn(cmd,spawnOpts)}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,cmd[0]??""))}let proc2=spawned,killBunTree=createProcessTreeKiller(proc2.pid,(sig)=>proc2.kill(sig),!0),killBunProcess=(sig)=>options?.killProcessTree?killBunTree(sig):Promise.resolve(proc2.kill(sig)),outputController2=createOutputOverflowController(maxBuffer,()=>{killBunProcess("SIGKILL").catch(()=>{return})}),timeoutHandle2;if(options?.killProcessTree===!0&&options.timeout&&options.timeout>0){if(timeoutHandle2=setTimeout(()=>{try{killBunProcess("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle2.unref==="function")timeoutHandle2.unref()}let exited2=proc2.exited.finally(()=>{if(timeoutHandle2!==void 0)clearTimeout(timeoutHandle2);outputController2.complete()});return{stdout:streamFromBun(proc2.stdout,maxBuffer,outputController2),stderr:streamFromBun(proc2.stderr,maxBuffer,outputController2),exited:exited2,get exitCode(){return proc2.exitCode},get signalCode(){return proc2.signalCode},kill(sig){killBunProcess(sig).catch(()=>{return})},killTree:killBunProcess}}let[file2,...args2]=cmd,detached=options?.killProcessTree===!0,mergedEnv=mergeEnvForChild(options?.env,options?.envOverrides),proc;try{proc=nodeSpawn(file2,args2,{cwd:options?.cwd,env:mergedEnv,detached,windowsHide:!0,windowsVerbatimArguments:options?.windowsVerbatimArguments,stdio:[mapStdio(options?.stdin),mapStdio(options?.stdout),mapStdio(options?.stderr)]})}catch(error49){return spawnCreationFailure(wrapSpawnFailure(error49,options?.cwd,file2))}let killChildTree=createProcessTreeKiller(proc.pid,(signal)=>proc.kill(signal),!0),killChild=(signal)=>{if(detached)return killChildTree(signal);return proc.kill(signal),Promise.resolve()},outputController=createOutputOverflowController(maxBuffer,()=>{killChild("SIGKILL").catch(()=>{return})}),timeoutHandle,observedSignal=null,observedSpawnError=null,exited=new Promise((resolve5)=>{if(proc.on("exit",(code,signal)=>{observedSignal=signal,resolve5(code??-1)}),proc.on("error",(error49)=>{observedSpawnError=wrapSpawnFailure(error49,options?.cwd,file2),resolve5(1)}),options?.timeout&&options.timeout>0){if(timeoutHandle=setTimeout(()=>{try{killChild("SIGKILL").catch(()=>{return})}catch{}},options.timeout),typeof timeoutHandle.unref==="function")timeoutHandle.unref()}}).finally(()=>{if(timeoutHandle!==void 0)clearTimeout(timeoutHandle);outputController.complete()});return{stdout:streamFromNode(proc.stdout,maxBuffer,outputController),stderr:streamFromNode(proc.stderr,maxBuffer,outputController),exited,get exitCode(){return observedSpawnError?null:proc.exitCode},get signalCode(){return observedSignal??proc.signalCode},get spawnError(){return observedSpawnError},kill(signal){killChild(signal).catch(()=>{return})},killTree:killChild}}function syncSpawnCreationFailure(error49){return{stdout:new Uint8Array(0),stderr:new TextEncoder().encode(error49.message),exitCode:SPAWN_CREATION_FAILURE_EXIT_CODE,success:!1}}function bunSpawnSync(cmd,options){let requestedCwd=Array.isArray(cmd)?options?.cwd:options?.cwd??cmd.cwd,executable=(Array.isArray(cmd)?cmd[0]:cmd.cmd[0])??"",bun=getBun();if(bun?.spawnSync){let mergedEnv2=mergeEnvForChild(options?.env,options?.envOverrides),spawnOpts={...options};if(delete spawnOpts.maxBuffer,mergedEnv2!==void 0)spawnOpts.env=mergedEnv2;try{return bun.spawnSync(cmd,spawnOpts)}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,requestedCwd,executable))}}let argv,mergedOptions;if(Array.isArray(cmd))argv=cmd,mergedOptions={...options??{}};else if(argv=cmd.cmd,mergedOptions={cwd:cmd.cwd,env:cmd.env,stdin:"pipe",timeout:cmd.timeout,...options??{}},cmd.stdin!==void 0)mergedOptions.stdin=cmd.stdin;let[file2,...args2]=argv,mergedEnv=mergeEnvForChild(mergedOptions.env,options?.envOverrides),result;try{result=nodeSpawnSync(file2,args2,{cwd:mergedOptions.cwd,env:mergedEnv,input:mergedOptions.stdin instanceof Uint8Array||typeof mergedOptions.stdin==="string"?mergedOptions.stdin:void 0,timeout:mergedOptions.timeout,windowsHide:!0})}catch(error49){return syncSpawnCreationFailure(wrapSpawnFailure(error49,mergedOptions.cwd,file2))}if(result.error){let wrapped=wrapSpawnFailure(result.error,mergedOptions.cwd,file2);if(wrapped instanceof SpawnCwdMissingError)return syncSpawnCreationFailure(wrapped)}let stdout=result.stdout instanceof Buffer?new Uint8Array(result.stdout.buffer,result.stdout.byteOffset,result.stdout.byteLength):typeof result.stdout==="string"?new TextEncoder().encode(result.stdout):new Uint8Array(0),stderr=result.stderr instanceof Buffer?new Uint8Array(result.stderr.buffer,result.stderr.byteOffset,result.stderr.byteLength):typeof result.stderr==="string"?new TextEncoder().encode(result.stderr):new Uint8Array(0),exitCode=result.status??(result.signal?128:1);return{stdout,stderr,exitCode,success:exitCode===0&&!result.error}}var WINDOWS_RENAME_MAX_RETRIES=3,WINDOWS_RENAME_RETRY_DELAY_MS=50,tempCounter=0,DEFAULT_BUN_SPAWN_MAX_BUFFER_BYTES=5242880,BunCompatOutputLimitError,_internals9,SpawnCwdMissingError,AMBIGUOUS_SPAWN_CODES,SPAWN_CREATION_FAILURE_EXIT_CODE=1;var init_bun_compat=__esm(()=>{BunCompatOutputLimitError=class BunCompatOutputLimitError extends Error{limit;captured;total;constructor(limit,captured,total){super(`Subprocess output exceeded the ${limit}-byte buffer limit after capturing ${captured} bytes (${total} bytes observed)`);this.name="BunCompatOutputLimitError",this.limit=limit,this.captured=captured,this.total=total}};_internals9={platform:()=>process.platform,cwd:()=>process.cwd(),spawnTaskkill:(args2,options)=>nodeSpawn("taskkill",args2,options),createProcessTreeKiller,statSync:(target)=>fsSync3.statSync(target)};SpawnCwdMissingError=class SpawnCwdMissingError extends Error{name="SpawnCwdMissingError";code="ENOENT";cwd;reason;executable;constructor(cwd,reason,executable,options){super(reason==="missing"?`cannot start "${executable}": working directory no longer exists: ${cwd}`:`cannot start "${executable}": working directory is not a directory: ${cwd}`,options);this.cwd=cwd,this.reason=reason,this.executable=executable}};AMBIGUOUS_SPAWN_CODES=new Set(["ENOENT","ENOTDIR","EACCES","EPERM"])});import*as fs5 from"node:fs";import*as path8 from"node:path";function isFailClosedHandler(value){return typeof value==="function"&&Object.hasOwn(value,"__failClosed")&&value.__failClosed===!0}function safeHook(fn2){return async(input,output)=>{try{await fn2(input,output)}catch(_error){let functionName=fn2.name||"unknown";if(_error instanceof SwarmError)warn(`Hook '${functionName}' failed: ${_error.message}
180
180
  → ${_error.guidance}`);else warn(`Hook function '${functionName}' failed:`,_error)}}}function composeHandlers(...fns){if(fns.length===0)return async()=>{};for(let fn2 of fns)if(isFailClosedHandler(fn2))throw Error("composeHandlers cannot wrap fail-closed handlers; use composeBlockingHandlers or await them directly");return async(input,output)=>{for(let fn2 of fns)await _internals10.safeHook(fn2)(input,output)}}function validateSwarmPath(directory,filename){if(/[\0]/.test(filename))throw Error("Invalid filename: contains null bytes");if(/\.\.[/\\]/.test(filename))throw Error("Invalid filename: path traversal detected");if(/^[A-Za-z]:[\\/]/.test(filename))throw Error("Invalid filename: path escapes .swarm directory");if(filename.startsWith("/"))throw Error("Invalid filename: path escapes .swarm directory");let baseDir=path8.normalize(path8.resolve(directory,".swarm")),resolved=path8.normalize(path8.resolve(baseDir,filename));if(process.platform==="win32"){if(!resolved.toLowerCase().startsWith((baseDir+path8.sep).toLowerCase()))throw Error("Invalid filename: path escapes .swarm directory")}else if(!resolved.startsWith(baseDir+path8.sep))throw Error("Invalid filename: path escapes .swarm directory");let realBaseDir;try{if(fs5.lstatSync(baseDir).isSymbolicLink())throw Error("Invalid filename: path escapes .swarm directory");realBaseDir=fs5.realpathSync(baseDir)}catch(error49){if(error49 instanceof Error&&error49.message==="Invalid filename: path escapes .swarm directory")throw error49;if(error49.code==="ENOENT")return resolved;throw Error("Invalid filename: failed to resolve .swarm directory")}let existingPath=resolved;while(!fs5.existsSync(existingPath)){let parent=path8.dirname(existingPath);if(parent===existingPath||!isPathWithin(parent,baseDir)){existingPath=baseDir;break}existingPath=parent}let realExistingPath;try{realExistingPath=fs5.realpathSync(existingPath)}catch(error49){if(error49.code==="ENOENT")realExistingPath=realBaseDir;else throw Error("Invalid filename: failed to resolve path")}if(!isPathWithin(realExistingPath,realBaseDir))throw Error("Invalid filename: path escapes .swarm directory");return resolved}function isPathWithin(candidate,base){let normalizedCandidate=path8.normalize(candidate),normalizedBase=path8.normalize(base);if(process.platform==="win32"){let candidateLower=normalizedCandidate.toLowerCase(),baseLower=normalizedBase.toLowerCase();return candidateLower===baseLower||candidateLower.startsWith(`${baseLower}${path8.sep}`)}return normalizedCandidate===normalizedBase||normalizedCandidate.startsWith(`${normalizedBase}${path8.sep}`)}async function readSwarmFileAsync(directory,filename,cache2,reader,useArtifactCache=!0){if(cache2!==void 0&&useArtifactCache){let key=`${directory}::${filename}`,cached2=cache2.get(key);if(cached2!==void 0)return cached2;let promise2=readSwarmFileAsync(directory,filename,void 0,reader,useArtifactCache);return cache2.set(key,promise2),promise2}let ENOENT_MAX_ATTEMPTS=5,ENOENT_RETRY_DELAY_MS=10,maxAttempts=6;for(let attempt=0;attempt<maxAttempts;attempt++){let resolvedPath="";try{resolvedPath=_internals10.validateSwarmPath(directory,filename);let read=async()=>{if(reader!==void 0)return reader(resolvedPath);return await bunFile(resolvedPath).text()};return useArtifactCache?await _internals10.readCachedTextFile(resolvedPath,read):await read()}catch(err){let code=err?.code;if(reader!==void 0&&(code===void 0||code==="ERR_ENCODING_INVALID_ENCODED_DATA"))throw err;if(code==="ENOENT"){if(!(resolvedPath!==""&&(wasRecentlyWrittenByThisProcess(resolvedPath,RECENT_WRITE_WINDOW_MS)||wasObservedToExist(resolvedPath))))return null;if(attempt>=ENOENT_MAX_ATTEMPTS-1)return null;await new Promise((resolve6)=>setTimeout(resolve6,ENOENT_RETRY_DELAY_MS));continue}if(!(code==="EBUSY"||code==="EPERM"||code==="EACCES")||attempt===maxAttempts-1)return null;let retryDelayMs=10*2**attempt;await new Promise((resolve6)=>setTimeout(resolve6,retryDelayMs))}}return null}function estimateTokensFromCharCount(chars){if(chars<=0)return 0;return Math.ceil(chars*TOKENS_PER_CHAR)}function estimateCharsForTokens(tokens){if(tokens<=0)return 0;return Math.floor(tokens/TOKENS_PER_CHAR)}function estimateTokens(text){if(!text)return 0;return estimateTokensFromCharCount(text.length)}var _internals10,TOKENS_PER_CHAR=0.33;var init_utils2=__esm(()=>{init_utils();init_atomic_write();init_bun_compat();init_swarm_artifact_cache();_internals10={safeHook,composeHandlers,validateSwarmPath,readSwarmFileAsync,readCachedTextFile}});import{createHash as createHash3}from"node:crypto";import{appendFileSync,mkdirSync as mkdirSync2}from"node:fs";import*as path9 from"node:path";function isBidiCodePoint(code){for(let i=0;i<BIDI_RANGES.length;i++){let[lo,hi]=BIDI_RANGES[i];if(code>=lo&&code<=hi)return!0}return!1}function sanitizeString(value){let result="";for(let i=0;i<value.length;i++){let code=value.codePointAt(i)??0;if(code>65535)result+=value[i],i++,result+=value[i];else if(code===0)result+="\\u0000";else if(code===27){if(i+1<value.length&&value[i+1]==="["){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=48&&next<=63)i++;else if(next>=32&&next<=47)i++;else if(next>=64&&next<=126){i++;break}else break}}else if(i+1<value.length&&value[i+1]==="]"){i++;while(i+1<value.length){let next=value.charCodeAt(i+1);if(next===7){i++;break}else if(next===27&&i+2<value.length&&value[i+2]==="\\"){i+=2;break}else i++}}else if(i+1<value.length){let next=value.charCodeAt(i+1);if(next>=32&&next<=47){i++;while(i+1<value.length){let b=value.charCodeAt(i+1);if(b>=48&&b<=126){i++;break}else if(b>=32&&b<=47)i++;else break}}else if(next>=48&&next<=126)i++}}else if(isBidiCodePoint(code));else result+=value[i]}return result}function sanitizeRecord(record2){for(let key of Object.keys(record2)){let value=record2[key];if(typeof value==="string")record2[key]=sanitizeString(value);else if(value!==null&&typeof value==="object")if(Array.isArray(value))for(let i=0;i<value.length;i++){let element=value[i];if(typeof element==="string")value[i]=sanitizeString(element);else if(element!==null&&typeof element==="object")sanitizeRecord(element)}else sanitizeRecord(value)}return record2}function computeBatchDigest(batchId){return createHash3(BATCH_DIGEST_ALGORITHM).update(batchId).digest("hex")}function sidecarRelativePath(batchDigest){return path9.join("lane-results",batchDigest,"candidates.jsonl")}function validateRecord(record2,schema,label){let result=schema.safeParse(record2);if(!result.success)throw Error(`Sidecar ${label} schema validation failed: ${result.error.issues.map((i)=>`${i.path.join(".")}: ${i.message}`).join("; ")}`)}function withLockfile(lockDir,write){let lockPath=path9.join(lockDir,".lock"),release=import_proper_lockfile.default.lockSync(lockPath,{realpath:!1});try{return write()}finally{release()}}function appendToSidecar(options,batchId,envelope,candidates,cleanAttestation){let batchDigest=options.batchDigest??computeBatchDigest(batchId),relPath=sidecarRelativePath(batchDigest),absPath=validateSwarmPath(options.projectRoot,relPath);validateRecord(envelope,SidecarEnvelopeSchema,"envelope");for(let i=0;i<candidates.length;i++)validateRecord(candidates[i],SidecarCandidateSchema,`candidate[${i}]`);if(cleanAttestation!==void 0)validateRecord(cleanAttestation,SidecarCleanAttestationSchema,"clean_attestation");mkdirSync2(path9.dirname(absPath),{recursive:!0});let sanitizedEnvelope=sanitizeRecord(structuredClone(envelope)),sanitizedCandidates=candidates.map((c)=>sanitizeRecord(structuredClone(c))),sanitizedCleanAttestation=cleanAttestation===void 0?void 0:sanitizeRecord(structuredClone(cleanAttestation)),lines=[JSON.stringify(sanitizedEnvelope)];if(sanitizedCleanAttestation)lines.push(JSON.stringify(sanitizedCleanAttestation));for(let candidate of sanitizedCandidates)lines.push(JSON.stringify(candidate));let payload=`${lines.join(`
181
181
  `)}
182
182
  `,doWrite=()=>{appendFileSync(absPath,payload,"utf-8")};if(options.useLockfile)withLockfile(path9.dirname(absPath),doWrite);else doWrite()}var import_proper_lockfile,BATCH_DIGEST_ALGORITHM="sha256",SidecarEnvelopeSchema,SidecarCleanAttestationSchema,SidecarCandidateCommon,SidecarCandidateSchema,BIDI_RANGES;var init_candidate_sidecar_store=__esm(()=>{init_zod();init_utils2();init_candidate_contract();import_proper_lockfile=__toESM(require_proper_lockfile(),1),SidecarEnvelopeSchema=exports_external.object({record_type:exports_external.literal("invocation"),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),row_format_version:exports_external.number().int().nonnegative(),producer:exports_external.string().optional(),produced_at:exports_external.string().min(1),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),format_families_detected:exports_external.array(exports_external.string()),candidate_count:exports_external.number().int().nonnegative(),parse_errors:exports_external.number().int().nonnegative(),malformed_rows:exports_external.number().int().nonnegative(),clean_attestation_count:exports_external.number().int().nonnegative().optional()}).strict(),SidecarCleanAttestationSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("base_explorer"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict(),exports_external.object({record_type:exports_external.literal("clean_attestation"),row_format_family:exports_external.literal("micro_lane"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),extracted_from_partial_source:exports_external.literal(!1),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),micro_lane:exports_external.string().min(1),coverage_scope:exports_external.string().min(CLEAN_COVERAGE_SCOPE_MIN_CHARS),evidence:exports_external.string().min(CLEAN_EVIDENCE_MIN_CHARS)}).strict()]),SidecarCandidateCommon={record_type:exports_external.literal("candidate"),row_format_version:exports_external.number().int().nonnegative(),record_version:exports_external.object({major:exports_external.number().int().nonnegative(),minor:exports_external.number().int().nonnegative()}),source_output_ref:exports_external.string().min(1),source_batch_id:exports_external.string().min(1),source_lane_id:exports_external.string().min(1),source_agent:exports_external.string().min(1),source_digest:exports_external.string().regex(/^[a-f0-9]{64}$/),sessionId:exports_external.string().min(1).optional(),parentSessionId:exports_external.string().min(1).optional(),producer:exports_external.string().optional(),extracted_from_partial_source:exports_external.boolean(),candidate_id:exports_external.string().min(1),severity:exports_external.enum(CANDIDATE_SEVERITIES),category:exports_external.string().min(1),file_line:exports_external.string().min(1),claim:exports_external.string().min(1),evidence_summary:exports_external.string().min(1),confidence:exports_external.enum(CANDIDATE_CONFIDENCES),risk_impact:exports_external.enum(PR_REVIEW_RISK_IMPACTS).optional(),risk_tags:exports_external.array(exports_external.enum(PR_REVIEW_RISK_TAGS)).optional()},SidecarCandidateSchema=exports_external.discriminatedUnion("row_format_family",[exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("base_explorer"),lane:exports_external.string().min(1),micro_lane:exports_external.null(),impact_context:exports_external.string().min(1),invariant_violated:exports_external.null()}).strict(),exports_external.object({...SidecarCandidateCommon,row_format_family:exports_external.literal("micro_lane"),lane:exports_external.null(),micro_lane:exports_external.string().min(1),impact_context:exports_external.null(),invariant_violated:exports_external.string().min(1)}).strict()]),BIDI_RANGES=[[8234,8238],[8294,8297]]});function detectRowFormatFamily(rowFields){let trimmed=rowFields.map((f)=>f.trim()),hasImpactContext=trimmed.length>7&&trimmed[7]!=="",hasInvariantViolated=trimmed.length>6&&trimmed[6]!=="";if(hasImpactContext&&!hasInvariantViolated)return"base_explorer";if(hasInvariantViolated&&!hasImpactContext)return"micro_lane";if(hasImpactContext&&hasInvariantViolated)return"base_explorer";throw new UnknownFormatFamilyError}function mapFields(fields,family){let trimmed=fields.map((f)=>f.trim()),names=CANDIDATE_FIELDS[family],result={};for(let i=0;i<names.length;i++)result[names[i]]=i<trimmed.length&&trimmed[i]!==""?trimmed[i]:null;if(family==="base_explorer")result.micro_lane=null,result.invariant_violated=null;else result.lane=null,result.impact_context=null;return result}function getRequiredFields(family){return CANDIDATE_REQUIRED_FIELDS[family]}function assertNonNullCandidateId(value){if(value===null||value==="")throw Error("Invariant violation: null/empty candidate_id reached candidate builder")}function buildInvocationEnvelope(input,flags,formatFamiliesDetected,candidateCount,parseErrors,malformedRows,cleanAttestationCount=0){return{record_type:"invocation",source_output_ref:input.output_ref,source_batch_id:input.batchId,source_lane_id:input.laneId,source_agent:input.agent,source_digest:input.digest,row_format_version:flags.row_format_version,sessionId:input.sessionId,parentSessionId:input.parentSessionId,...flags.producer?{producer:flags.producer}:{},produced_at:input.produced_at,record_version:RECORD_VERSION,format_families_detected:formatFamiliesDetected,candidate_count:candidateCount,parse_errors:parseErrors,malformed_rows:malformedRows,clean_attestation_count:cleanAttestationCount}}function buildEmptyDiagnostics(input,flags){return{candidate_count:0,parse_errors:0,parse_error_details:[],malformed_rows:0,duplicate_id_count:0,duplicate_id_warnings:[],degraded_source_count:flags.degraded?1:0,incomplete_source_count:input.transcriptIncomplete?1:0,format_families_detected:[],clean_attestation_count:0}}function refusalResult(errorCode,errorMessage,input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0);return{error:errorMessage,error_code:errorCode,candidates:[],invocation_envelope:envelope,diagnostics:buildEmptyDiagnostics(input,flags)}}function detectFormatMismatchHint(text){if(text.trim()==="")return;let severityPattern=/\b(CRITICAL|HIGH|MEDIUM|LOW|INFO)\b/,fileLinePattern=/\b\S+\.[a-z]{1,4}:\d+\b/,hasSeverity=severityPattern.test(text),textForFileLine=text.replace(/\b\w+:\/\/\S*/g,""),hasFileLine=fileLinePattern.test(textForFileLine);if(hasSeverity&&hasFileLine)return"Lane output contains severity keywords and file:line references but no parseable [CANDIDATE] rows. The explorer may have emitted findings in prose format instead of pipe-delimited candidate rows.";if(hasSeverity)return"Lane output contains severity keywords but no parseable [CANDIDATE] rows. The explorer may have emitted findings in an unstructured format.";return}function emptyTextResult(input,flags){let envelope=buildInvocationEnvelope(input,flags,[],0,0,0),diagnostics=buildEmptyDiagnostics(input,flags),hint=detectFormatMismatchHint(input.text);if(hint)diagnostics.format_mismatch_hint=hint;return{candidates:[],invocation_envelope:envelope,diagnostics}}function parseCandidates(input,flags){let inputParse=ArtifactInputSchema.safeParse(input);if(!inputParse.success)throw Error(`Invalid ArtifactInput: ${inputParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let flagsParse=ParseFlagsSchema.safeParse(flags);if(!flagsParse.success)throw Error(`Invalid ParseFlags: ${flagsParse.error.issues.map((issue2)=>issue2.message).join(", ")}`);let validatedInput=inputParse.data,validatedFlags=flagsParse.data;if(validatedInput.artifact_status==="ref-not-found")return refusalResult("ref-not-found","Artifact reference not found in store",validatedInput,validatedFlags);if(validatedInput.artifact_status==="artifact-corrupted")return refusalResult("artifact-corrupted","Artifact data is corrupted",validatedInput,validatedFlags);if(validatedFlags.degraded&&!validatedFlags.accept_degraded)return refusalResult("degraded-source-refused","Degraded source refused by caller",validatedInput,validatedFlags);if(validatedInput.transcriptIncomplete===!0&&!validatedFlags.accept_partial)return refusalResult("partial-source-refused","Partial transcript refused by caller",validatedInput,validatedFlags);if(validatedInput.text.trim()==="")return emptyTextResult(validatedInput,validatedFlags);return parseText(validatedInput,validatedFlags)}function parseText(input,flags){let lines=removeCandidateCodeFences(input.text).split(`
@@ -1261,7 +1261,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1261
1261
  `:"");writeLegacyStoreFile(legacyPath,legacyPayload),fs56.writeFileSync(projectionMarkerPath(legacyPath),"","utf-8"),legacyStat=fs56.statSync(legacyPath)}checkpoint.migration.sourceBytes=legacyStat.size,checkpoint.migration.scannedBytes=legacyStat.size,checkpoint.migration.sourceMtimeMs=legacyStat.mtimeMs}catch{}}flushAuditEvents(directory,events,checkpoint.sequence,checkpoint.maintenance);let archiveEvent=maybeArchiveLegacy(directory,checkpoint);if(archiveEvent)events.push(archiveEvent),checkpoint.sequence+=1,_internals81.writeCheckpointFile(directory,checkpoint),flushAuditEvents(directory,[archiveEvent],checkpoint.sequence,checkpoint.maintenance);cleanupStaleLegacyArchive(directory);let coordinationView=readCoordinationSubscriptions(directory);if(coordinationView!==null&&!isDeepStrictEqualByJson(coordinationView,loaded.view))persistCoordinationSubscriptions(directory,{...loaded.view});for(let kind of["compact","migrate-complete","archive","foreign-rebind","corrupt-quarantine"])if(events.some((event)=>event.kind===kind))emitHealthTelemetry(directory,kind,checkpoint)}async function subscribe(directory,input){if(!directory||directory.trim()==="")throw Error("directory is required");if(!input.sessionID||input.sessionID.trim()==="")throw Error("sessionID is required and must be non-empty");if(!input.repoFullName||input.repoFullName.trim()==="")throw Error("repoFullName is required and must be non-empty");if(!input.prUrl||input.prUrl.trim()==="")throw Error("prUrl is required and must be non-empty");if(!input.prNumber||!Number.isInteger(input.prNumber)||input.prNumber<=0)throw Error("prNumber is required and must be a positive integer");let correlationId=buildCorrelationId(input.sessionID,input.repoFullName,input.prNumber),now=Date.now();return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match2)return onSubscriptionCreated?.(directory,match2),match2;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record3={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record3),view[correlationId]=record3,persistCoordinationSubscriptions(directory,view,!0,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record3),record3}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(match)return onSubscriptionCreated?.(directory,match),finalizeWrite(directory,loaded,[]),match;if(input.maxSubscriptions===void 0||input.maxSubscriptions>0){let limit=input.maxSubscriptions!==void 0?input.maxSubscriptions:PR_SUBSCRIPTION_LIMITS.defaultMaxActiveSubscriptions,activeCount=Object.values(loaded.view).filter((r)=>r.status==="active").length;if(activeCount>=limit)throw Error(`PR subscription limit reached: ${activeCount}/${limit}`)}let record2={correlationId,sessionID:input.sessionID,prNumber:input.prNumber,repoFullName:input.repoFullName,prUrl:input.prUrl,lastCheckedAt:now,isWatching:!0,hasUnaddressedEvents:!1,status:"active",createdAt:now,updatedAt:now,errorCount:0};return validateRecord3(record2),loaded.view[correlationId]=record2,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"subscribe",correlationId}]),onSubscriptionCreated?.(directory,record2),record2})}async function unsubscribe(directory,correlationId){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;let removed2={...match2,status:"removed",isWatching:!1,updatedAt:Date.now()};return view[correlationId]=removed2,persistCoordinationSubscriptions(directory,view,!0,[{kind:"unsubscribe",correlationId}]),removed2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;let now=Date.now(),removed={...match,status:"removed",isWatching:!1,updatedAt:now};return loaded.view[correlationId]=removed,loaded.dirty=!0,finalizeWrite(directory,loaded,[{kind:"unsubscribe",correlationId}]),removed})}async function listActive(directory){let{view}=await loadViewForRead(directory);return Object.values(view).filter((r)=>r.status==="active")}async function lookupByPr(directory,repoFullName,prNumber){let{view}=await loadViewForRead(directory);for(let record2 of Object.values(view))if(record2.status==="active"&&record2.repoFullName===repoFullName&&record2.prNumber===prNumber)return record2;return null}async function updateSnapshot(directory,correlationId,updates){if(!correlationId)return null;return withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{let existingCoordination=readCoordinationSubscriptions(directory);if(existingCoordination!==null&&!fileExistsStrict(storePath3(directory))&&!hasLegacyReconciliationArtifacts(directory)){let match2=Object.values(existingCoordination).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),existingCoordination[correlationId]=updated2,persistCoordinationSubscriptions(directory,existingCoordination),updated2}if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},match2=Object.values(view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match2)return null;if(!snapshotUpdateHasChanges(match2,updates))return match2;let updated2={...match2,...updates,correlationId,sessionID:match2.sessionID,repoFullName:match2.repoFullName,prNumber:match2.prNumber,prUrl:match2.prUrl,createdAt:match2.createdAt,updatedAt:Date.now()};return validateRecord3(updated2),view[correlationId]=updated2,persistCoordinationSubscriptions(directory,view),updated2}let loaded=loadViewForWrite(directory),match=Object.values(loaded.view).find((r)=>r.correlationId===correlationId&&r.status==="active");if(!match)return finalizeWrite(directory,loaded,[]),null;if(!snapshotUpdateHasChanges(match,updates))return finalizeWrite(directory,loaded,[]),match;let updated={...match,...updates,correlationId,sessionID:match.sessionID,repoFullName:match.repoFullName,prNumber:match.prNumber,prUrl:match.prUrl,createdAt:match.createdAt,updatedAt:Date.now()};return validateRecord3(updated),loaded.view[correlationId]=updated,loaded.dirty=!0,finalizeWrite(directory,loaded,[]),updated})}async function sweepStale(directory,ttlDays,mergedPrs){if(!ttlDays||ttlDays<=0)return 0;let ttlMs=ttlDays*86400000,now=Date.now();try{return await withEvidenceLock(directory,PR_SUBSCRIPTIONS_FILE,STORE_LOCK_AGENT,STORE_LOCK_TASK,async()=>{if(canUseCoordinationWritePath(directory)){let view=readCoordinationSubscriptions(directory)??{},swept2=0,expiredCorrelationIds=[],now2=Date.now();for(let record2 of Object.values(view)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now2-record2.updatedAt>ttlMs;if(isMerged||isStale&&!record2.hasUnaddressedEvents)view[record2.correlationId]={...record2,status:"expired",isWatching:!1,updatedAt:now2},expiredCorrelationIds.push(record2.correlationId),swept2+=1}if(swept2>0)persistCoordinationSubscriptions(directory,view,!0,expiredCorrelationIds.map((correlationId)=>({kind:"expired",correlationId})));return swept2}let loaded=loadViewForWrite(directory),opAudit=[],swept=0;for(let record2 of Object.values(loaded.view)){if(record2.status!=="active")continue;let prKey=`${record2.repoFullName}::${record2.prNumber}`,isMerged=mergedPrs?.has(prKey)??!1,isStale=now-record2.updatedAt>ttlMs;if(isMerged){loaded.view[record2.correlationId]={...record2,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record2.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: merged/closed: ${prKey}`);continue}if(isStale&&!record2.hasUnaddressedEvents)loaded.view[record2.correlationId]={...record2,status:"expired",isWatching:!1,updatedAt:now},swept+=1,opAudit.push({kind:"expired",correlationId:record2.correlationId}),loaded.dirty=!0,log(`[pr-monitor] Swept subscription: stale (TTL ${ttlDays}d): ${prKey}`)}return finalizeWrite(directory,loaded,opAudit),swept})}catch(err){return log(`[pr-monitor] sweepStale failed: ${err instanceof Error?err.message:String(err)}`),0}}async function getPrSubscriptionHealth(directory){try{let coordinationView=readCoordinationSubscriptions(directory),read=readCheckpoint(directory),migrationPending=read.kind==="ok"&&sameProjectRoot(read.value.rootPath,directory)&&read.value.migration?.done===!1;if(coordinationView!==null&&Object.keys(coordinationView).length>0&&!migrationPending){let audit2=auditStats(directory),archiveBytes2=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes2=fileSizeOrNull(checkpointPath(directory))??0,health2=healthFromView(coordinationView,buildCoordinationProjectionCheckpoint(directory,coordinationView));return health2.recoverySource="checkpoint",applyFileStats(health2,checkpointBytes2,audit2,archiveBytes2),health2}let audit=auditStats(directory),archiveBytes=fileSizeOrNull(legacyArchivePath(directory))??0,checkpointBytes=fileSizeOrNull(checkpointPath(directory))??0,legacySize=fileSizeOrNull(storePath3(directory)),legacyOverLimit=legacySize!==null&&legacySize>PR_SUBSCRIPTION_LIMITS.legacySourceMaxBytes,health;if(read.kind==="ok"&&!sameProjectRoot(read.value.rootPath,directory))health=emptyHealth2(),health.recoverySource="foreign";else if(read.kind==="invalid"){if(legacySize!==null&&!legacyOverLimit){let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}else health=emptyHealth2();health.recoverySource="corrupt-recovered"}else if(read.kind==="absent"){if(legacySize===null||legacyOverLimit)health=emptyHealth2();else{let fold=foldLegacyRegion(storePath3(directory),0,Number.MAX_SAFE_INTEGER),view={};if(!fold.ioError)mergeFoldedRecords(view,fold.folded);health=healthFromView(view,freshCheckpoint(directory)),health.corruptLegacyRecords=fold.corruptLines}health.recoverySource=legacySize===null?"empty":"legacy-log"}else{let pendingCheckpoint=migrationPending&&coordinationView!==null?(()=>{let merged=cloneCheckpoint(read.value);return merged.records={...merged.records,...coordinationView},merged})():read.value,overlaid=overlayLegacy(directory,pendingCheckpoint);health=healthFromView(overlaid.view,read.value),health.recoverySource=overlaid.usedLegacy?"checkpoint+legacy":"checkpoint"}return health.legacyOverLimit=legacyOverLimit,applyFileStats(health,checkpointBytes,audit,archiveBytes),health}catch(err){return log(`[pr-monitor] getPrSubscriptionHealth failed: ${storageErrorCode(err)}`),emptyHealth2()}}function applyFileStats(health,checkpointBytes,audit,archiveBytes){health.checkpointBytes=checkpointBytes,health.pressurePct=checkpointBytes===0?0:Math.round(checkpointBytes/health.checkpointLimitBytes*1000)/10,health.auditLines=audit.lines,health.auditBytes=audit.bytes,health.legacyArchiveBytes=archiveBytes}function emptyHealth2(){return{schemaVersion:1,sequence:0,checkpointAgeMs:null,checkpointBytes:0,checkpointLimitBytes:PR_SUBSCRIPTION_LIMITS.maxCheckpointBytes,pressurePct:0,activeCount:0,removedCount:0,expiredCount:0,terminalSummary:{removed:0,expired:0,lastTerminalAt:null},auditLines:0,auditBytes:0,auditLimitBytes:PR_SUBSCRIPTION_LIMITS.auditMaxBytesHigh,compactions:0,corruptLegacyRecords:0,droppedAuditTransitions:0,resets:0,recoverySource:"empty",migration:null,legacyArchiveBytes:0,legacyOverLimit:!1}}function healthFromView(view,checkpoint){let records=Object.values(view),health=emptyHealth2();return health.sequence=checkpoint.sequence,health.checkpointAgeMs=checkpoint.sequence>0?Date.now()-checkpoint.updatedAt:null,health.activeCount=records.filter((r)=>r.status==="active").length,health.removedCount=records.filter((r)=>r.status==="removed").length,health.expiredCount=records.filter((r)=>r.status==="expired").length,health.terminalSummary={...checkpoint.terminalSummary},health.compactions=checkpoint.maintenance.compactions,health.corruptLegacyRecords=checkpoint.maintenance.corruptLegacyRecords,health.droppedAuditTransitions=checkpoint.maintenance.droppedAuditTransitions,health.resets=checkpoint.maintenance.resets,health.migration=checkpoint.migration?{done:checkpoint.migration.done,scannedBytes:checkpoint.migration.scannedBytes,sourceBytes:checkpoint.migration.sourceBytes}:null,health}var PR_SUBSCRIPTIONS_FILE="pr-monitor/subscriptions.jsonl",PR_SUBSCRIPTIONS_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.json",PR_SUBSCRIPTIONS_AUDIT_FILE="pr-monitor/subscriptions.audit.jsonl",LEGACY_ARCHIVE_FILE="pr-monitor/subscriptions.legacy.jsonl",FOREIGN_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.foreign.json",CORRUPT_CHECKPOINT_FILE="pr-monitor/subscriptions.checkpoint.corrupt.json",FOREIGN_LEGACY_FILE="pr-monitor/subscriptions.legacy.foreign.jsonl",PR_SUBSCRIPTION_COORDINATION_NAMESPACE="background.pr-subscription",STORE_LOCK_AGENT="pr-monitor",STORE_LOCK_TASK="pr-subscriptions",PR_SUBSCRIPTION_LIMITS,onSubscriptionCreated=null,prMonitorWorkerHandlers,MAX_PR_MONITOR_WORKER_HANDLERS=64,RecordSchema,TerminalSummarySchema,MigrationSchema,MaintenanceSchema,CheckpointSchema,PrSubscriptionCapacityError,legacyOverLimitWarned,migrationCapacityWarned,bootstrapAttempted,_internals81;var init_pr_subscriptions=__esm(()=>{init_zod();init_db();init_lock();init_learning_health();init_utils2();init_telemetry();init_utils();init_atomic_write();init_canonical_root();PR_SUBSCRIPTION_LIMITS={readChunkBytes:65536,maxRecordBytes:65536,migrationChunkBytes:1048576,migrationMaxBytesPerOperation:8388608,legacySourceMaxBytes:67108864,defaultMaxActiveSubscriptions:20,maxCheckpointRecords:512,maxCheckpointBytes:262144,checkpointHardReadBytes:1048576,terminalRecordsHigh:60,terminalRecordsLow:30,terminalMaxAgeMs:2592000000,auditMaxLinesHigh:500,auditMaxLinesLow:250,auditMaxBytesHigh:131072,auditMaxBytesLow:65536,legacyArchiveTtlMs:604800000,bootstrapLockTimeoutMs:5000};prMonitorWorkerHandlers=new Map;RecordSchema=exports_external.object({correlationId:exports_external.string().min(1),sessionID:exports_external.string().min(1),prNumber:exports_external.number().int().positive(),repoFullName:exports_external.string().regex(/^[^/]+\/[^/]+$/,"Must be owner/repo format"),prUrl:exports_external.string().min(1).regex(/^https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+$/,"Must be a valid GitHub PR URL"),headRefOid:exports_external.string().optional(),lastCheckedAt:exports_external.number(),lastCommentId:exports_external.string().optional(),lastCheckRunSet:exports_external.string().optional(),mergeableState:exports_external.string().optional(),mergeGroupRunStatus:exports_external.string().optional(),mergeGroupRunConclusion:exports_external.string().optional(),mergeGroupRunHtmlUrl:exports_external.string().optional(),isWatching:exports_external.boolean(),hasUnaddressedEvents:exports_external.boolean(),status:exports_external.enum(["active","removed","expired"]),createdAt:exports_external.number(),updatedAt:exports_external.number(),errorCount:exports_external.number().int().min(0),customPollIntervalSeconds:exports_external.number().int().positive().optional(),customFailureThreshold:exports_external.number().int().min(0).optional(),customCooldownSeconds:exports_external.number().int().min(0).optional()}).strict(),TerminalSummarySchema=exports_external.object({removed:exports_external.number().int().min(0),expired:exports_external.number().int().min(0),lastTerminalAt:exports_external.number().int().nullable()}).strict(),MigrationSchema=exports_external.object({scannedBytes:exports_external.number().int().nonnegative(),sourceBytes:exports_external.number().int().nonnegative(),sourceMtimeMs:exports_external.number().nonnegative(),corruptLines:exports_external.number().int().nonnegative(),discardingOversizeLine:exports_external.boolean().optional().default(!1),baselineRecords:exports_external.record(exports_external.string(),RecordSchema).optional().default({}),baselineTerminalSummary:TerminalSummarySchema.optional().default({removed:0,expired:0,lastTerminalAt:null}),done:exports_external.boolean(),archived:exports_external.boolean(),startedAt:exports_external.number().int().nonnegative()}).strict(),MaintenanceSchema=exports_external.object({compactions:exports_external.number().int().nonnegative(),droppedAuditTransitions:exports_external.number().int().nonnegative(),corruptLegacyRecords:exports_external.number().int().nonnegative(),lastCompactedAt:exports_external.number().int().nullable(),resets:exports_external.number().int().nonnegative()}).strict(),CheckpointSchema=exports_external.object({schemaVersion:exports_external.literal(1),sequence:exports_external.number().int().positive(),rootPath:exports_external.string().min(1).max(4096),updatedAt:exports_external.number().int().nonnegative(),records:exports_external.record(exports_external.string(),RecordSchema),terminalSummary:TerminalSummarySchema,migration:MigrationSchema.nullable(),maintenance:MaintenanceSchema}).strict();PrSubscriptionCapacityError=class PrSubscriptionCapacityError extends Error{constructor(message){super(message);this.name="PrSubscriptionCapacityError"}};legacyOverLimitWarned=new Map;migrationCapacityWarned=new Map;bootstrapAttempted=new Map;_internals81={afterCheckpointFstat:(_filePath)=>{},archiveStatSync:fs56.statSync,auditCompactionWrite:atomicWriteSwarmFileSync,beforeBootstrapLock:(_directory2)=>{},beforeArchiveLegacy:(_directory2)=>{},beforeArchiveRename:(_directory2)=>{},foldLegacyRegion,legacyCloseSync:fs56.closeSync,legacyFstatSync:fs56.fstatSync,mergeFoldedRecords,readSync:fs56.readSync,renameWithRetry:renameWithRetry5,sameProjectRoot,statSync:fs56.statSync,writeCheckpointFile}});var exports_state={};__export(exports_state,{updateTaskWorkflowCache:()=>updateTaskWorkflowCache,updateAgentEventTime:()=>updateAgentEventTime,takeReviewerScopeGeneration:()=>takeReviewerScopeGeneration,sweepStaleSessions:()=>sweepStaleSessions,swarmState:()=>swarmState,startReviewerScopeGeneration:()=>startReviewerScopeGeneration,startAgentSession:()=>startAgentSession,settleReviewerScopeMergeback:()=>settleReviewerScopeMergeback,setSessionEnvironment:()=>setSessionEnvironment,setSessionBudget:()=>setSessionBudget,setLiveContextWindow:()=>setLiveContextWindow,setFinalPromptPressure:()=>setFinalPromptPressure,setFinalAccountingWarningBand:()=>setFinalAccountingWarningBand,setCriticalShownIds:()=>setCriticalShownIds,reviewerScopeGenerationHasDeclaredOverlap:()=>reviewerScopeGenerationHasDeclaredOverlap,resolveSessionWorkspaceDirectory:()=>resolveSessionWorkspaceDirectory,resetSwarmStatePreservingSingletons:()=>resetSwarmStatePreservingSingletons,resetSwarmState:()=>resetSwarmState,resetModifiedFilesForTask:()=>resetModifiedFilesForTask,reserveStageBRouteEvidence:()=>reserveStageBRouteEvidence,rehydrateSessionFromDisk:()=>rehydrateSessionFromDisk,rehydratePrSubscriptions:()=>rehydratePrSubscriptions,recordStageBRouteEvidence:()=>recordStageBRouteEvidence,recordStageBCompletion:()=>recordStageBCompletion,recordSessionWorkspaceRoot:()=>recordSessionWorkspaceRoot,recordReviewerScopeGenerationFileFingerprint:()=>recordReviewerScopeGenerationFileFingerprint,recordReviewerScopeGenerationFile:()=>recordReviewerScopeGenerationFile,recordReviewerScopeGenerationCaptureFailure:()=>recordReviewerScopeGenerationCaptureFailure,recordPhaseAgentDispatch:()=>recordPhaseAgentDispatch,recordModifiedFilesForTask:()=>recordModifiedFilesForTask,recordModifiedFileForTask:()=>recordModifiedFileForTask,pruneOldWindows:()=>pruneOldWindows,peekReviewerScopeGenerationClaim:()=>peekReviewerScopeGenerationClaim,peekReviewerScopeGenerationByStatus:()=>peekReviewerScopeGenerationByStatus,peekReadyReviewerScopeGeneration:()=>peekReadyReviewerScopeGeneration,maybeSweepStaleSessions:()=>maybeSweepStaleSessions,markStageBRouteRequired:()=>markStageBRouteRequired,markReviewerScopeGenerationReady:()=>markReviewerScopeGenerationReady,markReviewerScopeGenerationNoChange:()=>markReviewerScopeGenerationNoChange,markReviewerScopeGenerationMergebackPending:()=>markReviewerScopeGenerationMergebackPending,isStageBRouteRequired:()=>isStageBRouteRequired,isReviewerScopeGenerationCurrent:()=>isReviewerScopeGenerationCurrent,isCouncilGateActive:()=>isCouncilGateActive,incrementGateDenialCount:()=>incrementGateDenialCount,hasBothStageBCompletions:()=>hasBothStageBCompletions,hasActiveTurboMode:()=>hasActiveTurboMode,hasActiveLeanTurbo:()=>hasActiveLeanTurbo,hasActiveFullAuto:()=>hasActiveFullAuto,hasActiveEpicMode:()=>hasActiveEpicMode,getTaskState:()=>getTaskState,getStageBRouteEvidence:()=>getStageBRouteEvidence,getSessionEnvironment:()=>getSessionEnvironment,getSessionBudgetTokens:()=>getSessionBudgetTokens,getSessionBudgetPct:()=>getSessionBudgetPct,getRunContext:()=>getRunContext,getReviewerScopeOwnershipHistory:()=>getReviewerScopeOwnershipHistory,getReviewerScopeGenerationForCoderCall:()=>getReviewerScopeGenerationForCoderCall,getResolvedAutoProceed:()=>getResolvedAutoProceed,getModifiedFilesForTask:()=>getModifiedFilesForTask,getLiveContextWindow:()=>getLiveContextWindow,getLiveContextModelIdentity:()=>getLiveContextModelIdentity,getFinalPromptPressure:()=>getFinalPromptPressure,getFinalAccountingWarningBand:()=>getFinalAccountingWarningBand,getDisplayFinalPromptPressure:()=>getDisplayFinalPromptPressure,getDisplayBudget:()=>getDisplayBudget,getAgentSession:()=>getAgentSession,getActiveWindow:()=>getActiveWindow,getActiveFullAutoSessionID:()=>getActiveFullAutoSessionID,ensureSessionEnvironment:()=>ensureSessionEnvironment,ensureAgentSession:()=>ensureAgentSession,endAgentSession:()=>endAgentSession,discardReviewerScopeGenerationForCoderCall:()=>discardReviewerScopeGenerationForCoderCall,discardReviewerScopeGenerationClaim:()=>discardReviewerScopeGenerationClaim,defaultRunContext:()=>defaultRunContext,completeModifiedFilesForTask:()=>completeModifiedFilesForTask,clearStageBRouteRequired:()=>clearStageBRouteRequired,clearStageBRouteEvidence:()=>clearStageBRouteEvidence,clearGateDenialCount:()=>clearGateDenialCount,clearFinalAccountingWarningBands:()=>clearFinalAccountingWarningBands,clearCriticalShownIds:()=>clearCriticalShownIds,claimReviewerScopeGeneration:()=>claimReviewerScopeGeneration,canAdvanceTaskState:()=>canAdvanceTaskState,buildRehydrationCache:()=>buildRehydrationCache,buildGateDenialDirectiveKey:()=>buildGateDenialDirectiveKey,beginInvocation:()=>beginInvocation,attachReviewerScopeGenerationDispatchSnapshot:()=>attachReviewerScopeGenerationDispatchSnapshot,applyRehydrationCache:()=>applyRehydrationCache,advanceTaskStateAndPersist:()=>advanceTaskStateAndPersist,advanceTaskState:()=>advanceTaskState,addKnowledgeAckDedup:()=>addKnowledgeAckDedup,_resetCouncilDisagreementWarnings:()=>_resetCouncilDisagreementWarnings,_internals:()=>_internals82,REVIEWER_SCOPE_GENERATION_TTL_MS:()=>REVIEWER_SCOPE_GENERATION_TTL_MS,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS:()=>MAX_TRACKED_TASK_FILE_ATTRIBUTIONS,MAX_TRACKED_KNOWLEDGE_ACKS:()=>MAX_TRACKED_KNOWLEDGE_ACKS,MAX_TRACKED_GATE_DENIALS:()=>MAX_TRACKED_GATE_DENIALS,MAX_TRACKED_CRITICAL_SHOWN:()=>MAX_TRACKED_CRITICAL_SHOWN,MAX_TRACKED_CONTEXT_WINDOWS:()=>MAX_TRACKED_CONTEXT_WINDOWS,MAX_TRACKED_BUDGET_SESSIONS:()=>MAX_TRACKED_BUDGET_SESSIONS,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY:()=>MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY,MAX_REVIEWER_SCOPE_GENERATION_FILES:()=>MAX_REVIEWER_SCOPE_GENERATION_FILES,MAX_REVIEWER_SCOPE_GENERATIONS:()=>MAX_REVIEWER_SCOPE_GENERATIONS,AgentRunContext:()=>AgentRunContext});import{randomUUID as randomUUID13}from"node:crypto";import*as fs57 from"node:fs/promises";import*as path92 from"node:path";function compareWorkflowStatePrecedence(left,right){return compareTaskWorkflowStateRank(left,right)}function cloneReviewerScopeGeneration(generation){return{...generation,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((entry)=>({...entry})),captureFailures:generation.captureFailures.map((entry)=>({...entry})),reviewerDispatchScope:generation.reviewerDispatchScope?{...generation.reviewerDispatchScope,files:[...generation.reviewerDispatchScope.files]}:void 0}}function cloneReviewerScopeOwnershipTombstone(tombstone){return{...tombstone,declaredFiles:[...tombstone.declaredFiles],modifiedFiles:[...tombstone.modifiedFiles],modifiedFileFingerprints:tombstone.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2}))}}function createNonTransientCircuitState(agentName,invocationId){return{ownerAgent:stripKnownSwarmPrefix(agentName),ownerInvocationId:invocationId,category:null,sameCategoryCount:0,hardStop:!1,lastSignal:null}}function getRunContext(runId){if(!runId)return defaultRunContext;return _runContexts.get(runId)??defaultRunContext}function resetSwarmState(){swarmState.activeToolCalls.clear(),swarmState.toolAggregates.clear(),swarmState.activeAgent.clear(),swarmState.delegationChains.clear(),swarmState.pendingEvents=0,swarmState.lastBudgetBySession.clear(),swarmState.finalPromptPressureBySession.clear(),clearAllTurnLedgers(),swarmState.finalAccountingWarningBandsBySession.clear(),swarmState.liveContextWindows.clear(),swarmState.agentSessions.clear(),clearSnapshotSessionOwnerships(),_lastIdleSweepAtMs=0,clearTrajectoryCache(),clearTrajectoryStepCounters(),swarmState.pendingRehydrations.clear(),swarmState.opencodeClient=null,swarmState.curatorInitAgentNames=[],swarmState.curatorPhaseAgentNames=[],swarmState.curatorPostmortemAgentNames=[],swarmState.curatorConsolidationAgentNames=[],swarmState.skillImproverAgentNames=[],swarmState.specWriterAgentNames=[],swarmState.currentCriticalShownIds.clear(),swarmState.knowledgeAckDedup.clear(),swarmState.gateDenialCounts.clear(),swarmState.generatedAgentNames=[],clearHydrationOwnershipState(),swarmState.fullAutoEnabledInConfig=!1,swarmState.environmentProfiles.clear(),clearAllActionCircuits(),clearAllTaskModelRoutingState(),clearPendingCoderScope();for(let binding of clearScopeBindings())clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});resetStandardWorktreeIsolationState(),resetRealtimeLearningNudgeState(),_councilDisagreementWarned.clear()}function resetSwarmStatePreservingSingletons(){let{opencodeClient:preservedOpencodeClient,fullAutoEnabledInConfig:preservedFullAutoEnabledInConfig,curatorInitAgentNames:preservedCuratorInitAgentNames,curatorPhaseAgentNames:preservedCuratorPhaseAgentNames,curatorPostmortemAgentNames:preservedCuratorPostmortemAgentNames,curatorConsolidationAgentNames:preservedCuratorConsolidationAgentNames,skillImproverAgentNames:preservedSkillImproverAgentNames,specWriterAgentNames:preservedSpecWriterAgentNames,generatedAgentNames:preservedGeneratedAgentNames}=swarmState;resetSwarmState(),swarmState.opencodeClient=preservedOpencodeClient,swarmState.fullAutoEnabledInConfig=preservedFullAutoEnabledInConfig,swarmState.curatorInitAgentNames=preservedCuratorInitAgentNames,swarmState.curatorPhaseAgentNames=preservedCuratorPhaseAgentNames,swarmState.curatorPostmortemAgentNames=preservedCuratorPostmortemAgentNames,swarmState.curatorConsolidationAgentNames=preservedCuratorConsolidationAgentNames,swarmState.skillImproverAgentNames=preservedSkillImproverAgentNames,swarmState.specWriterAgentNames=preservedSpecWriterAgentNames,swarmState.generatedAgentNames=preservedGeneratedAgentNames}function isBoundedGenerationValue(value,maxLength){return value.length>0&&value.length<=maxLength&&!Array.from(value).some((char)=>{let code=char.charCodeAt(0);return code<=31||code===127})}function reviewerScopeGenerationKey(taskId,coderCallID,generation){return`${taskId}\x00${coderCallID}\x00${generation}`}function reviewerScopeOwnershipKey(taskId,coderCallID,generation,sessionIncarnation){return`${taskId}\x00${coderCallID}\x00${generation}\x00${sessionIncarnation}`}function ensureReviewerScopeGenerationState(session){return session.reviewerScopeGenerations??=new Map,session.reviewerScopeGenerationCounter??=0,session.reviewerScopeIncarnation??=randomUUID13(),session.reviewerScopeLatestGenerationByTask??=new Map,session.reviewerScopeOwnershipHistory??=new Map,{generations:session.reviewerScopeGenerations,counter:session.reviewerScopeGenerationCounter,incarnation:session.reviewerScopeIncarnation,latestByTask:session.reviewerScopeLatestGenerationByTask,ownershipHistory:session.reviewerScopeOwnershipHistory}}function sweepReviewerScopeGenerations(session,now){let{generations}=ensureReviewerScopeGenerationState(session);for(let[key2,entry]of generations){if(entry.status==="claimed"||entry.status==="mergeback_pending"||entry.status==="mergeback_mismatch")continue;if(!Number.isFinite(entry.createdAt)||now<entry.createdAt||now-entry.createdAt>REVIEWER_SCOPE_GENERATION_TTL_MS)generations.delete(key2)}}function startReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512)||!input.captureDirectory.trim()||!input.workspaceIdentity.trim())return null;let now=input.createdAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations,counter,incarnation,latestByTask}=ensureReviewerScopeGenerationState(session);for(let[key3,entry]of generations)if(entry.taskId===input.taskId&&entry.status!=="claimed")generations.delete(key3);while(generations.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestUnclaimed=[...generations.entries()].find(([,entry])=>entry.status!=="claimed")?.[0];if(!oldestUnclaimed)return null;generations.delete(oldestUnclaimed)}session.reviewerScopeGenerationCounter=counter>=Number.MAX_SAFE_INTEGER?1:counter+1;let generation={taskId:input.taskId,coderCallID:input.coderCallID,generation:session.reviewerScopeGenerationCounter,sessionIncarnation:incarnation,background:input.background===!0,captureDirectory:input.captureDirectory,workspaceIdentity:input.workspaceIdentity,declaredFiles:[...new Set(input.declaredFiles??[])],modifiedFiles:[],modifiedFileFingerprints:[],captureFailures:[],status:"collecting",createdAt:now};if(!latestByTask.has(generation.taskId))while(latestByTask.size>=MAX_REVIEWER_SCOPE_GENERATIONS){let oldestTask=latestByTask.keys().next().value;if(!oldestTask)break;latestByTask.delete(oldestTask)}latestByTask.delete(generation.taskId),latestByTask.set(generation.taskId,{generation:generation.generation,coderCallID:generation.coderCallID,sessionIncarnation:generation.sessionIncarnation});let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.set(key2,generation),cloneReviewerScopeGeneration(generation)}function recordReviewerScopeGenerationFile(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096)||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.coderCallID,512))return!1;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.includes(input.file))return!0;if(generation.modifiedFiles.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES){let key2=reviewerScopeGenerationKey(generation.taskId,generation.coderCallID,generation.generation);return generations.delete(key2),!1}return generation.modifiedFiles.push(input.file),!0}function recordReviewerScopeGenerationFileFingerprint(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(!generation.modifiedFiles.includes(input.fingerprint.file))return!1;generation.captureFailures=generation.captureFailures.filter((entry)=>entry.file!==input.fingerprint.file);let existingIndex=generation.modifiedFileFingerprints.findIndex((entry)=>entry.file===input.fingerprint.file);if(existingIndex>=0)return generation.modifiedFileFingerprints[existingIndex]={...input.fingerprint},!0;if(generation.modifiedFileFingerprints.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)return!1;return generation.modifiedFileFingerprints.push({...input.fingerprint}),!0}function recordReviewerScopeGenerationCaptureFailure(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.file,4096))return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0],now=input.at??Date.now();generation.modifiedFileFingerprints=generation.modifiedFileFingerprints.filter((entry)=>entry.file!==input.file);let existingIndex=generation.captureFailures.findIndex((entry)=>entry.file===input.file);if(existingIndex>=0){let existing=generation.captureFailures[existingIndex];return generation.captureFailures[existingIndex]={...existing,code:input.code,retryable:input.retryable,attempts:existing.attempts+1,at:now},!0}if(generation.captureFailures.length>=MAX_REVIEWER_SCOPE_GENERATION_FILES)generation.captureFailures.shift();return generation.captureFailures.push({file:input.file,code:input.code,retryable:input.retryable,attempts:1,at:now}),!0}function markReviewerScopeGenerationReady(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.readyAt??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;let generation=matches[0];if(generation.status==="ready")return!0;if(input.primaryWorkspaceIdentity&&generation.workspaceIdentity!==input.primaryWorkspaceIdentity)return!1;if(!(generation.modifiedFiles.length===generation.modifiedFileFingerprints.length&&generation.modifiedFiles.every((file2)=>generation.modifiedFileFingerprints.some((entry)=>entry.file===file2))))return!1;return generation.status="ready",generation.readyAt=now,!0}function markReviewerScopeGenerationNoChange(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let now=input.at??Date.now();sweepReviewerScopeGenerations(session,now);let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.coderCallID===input.coderCallID&&entry.status==="collecting");if(matches.length!==1)return!1;let generation=matches[0];if(generation.modifiedFiles.length!==0)return!1;return generation.status="no_change",generation.readyAt=now,!0}function markReviewerScopeGenerationMergebackPending(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&(entry.status==="collecting"||entry.status==="ready"));if(matches.length!==1)return!1;if(matches[0].status==="mergeback_pending")return!0;return matches[0].status="mergeback_pending",!0}function settleReviewerScopeMergeback(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status==="mergeback_pending");if(matches.length!==1)return!1;let generation=matches[0],now=input.outcome.at??Date.now();if(input.outcome.verified){if(generation.status="ready",generation.readyAt===void 0)generation.readyAt=now;return generation.mergeback={verifiedAt:now,primaryWorkspaceIdentity:input.outcome.primaryWorkspaceIdentity},generation.captureDirectory=input.outcome.primaryDirectory,generation.workspaceIdentity=input.outcome.primaryWorkspaceIdentity,!0}return generation.status="mergeback_mismatch",generation.mergeback={failedAt:now,reason:input.outcome.reason},!0}function getReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.coderCallID===input.coderCallID&&(input.taskId===void 0||entry.taskId===input.taskId));return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReadyReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function peekReviewerScopeGenerationByStatus(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status===input.status);return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function claimReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session||!isBoundedGenerationValue(input.taskId,512)||!isBoundedGenerationValue(input.reviewerCallID,512))return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.status==="ready");if(matches.length!==1)return null;return matches[0].status="claimed",matches[0].reviewerCallID=input.reviewerCallID,cloneReviewerScopeGeneration(matches[0])}function attachReviewerScopeGenerationDispatchSnapshot(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed"&&entry.coderCallID===input.snapshot.coderCallID&&entry.generation===input.snapshot.generation&&entry.sessionIncarnation===input.snapshot.sessionIncarnation);if(matches.length!==1)return!1;return matches[0].reviewerDispatchScope={...input.snapshot,files:[...input.snapshot.files]},!0}function takeReviewerScopeGeneration(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return null;let[key2,generation]=matches[0];if(generation.background===!0&&generation.readyAt!==void 0&&Number.isFinite(generation.createdAt)&&Number.isFinite(generation.readyAt)){let{ownershipHistory}=ensureReviewerScopeGenerationState(session);while(ownershipHistory.size>=MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY){let oldestKey=ownershipHistory.keys().next().value;if(!oldestKey)break;ownershipHistory.delete(oldestKey)}let tombstone={parentSessionID:input.parentSessionID,taskId:generation.taskId,coderCallID:generation.coderCallID,generation:generation.generation,sessionIncarnation:generation.sessionIncarnation,background:!0,captureDirectory:generation.captureDirectory,workspaceIdentity:generation.workspaceIdentity,declaredFiles:[...generation.declaredFiles],modifiedFiles:[...generation.modifiedFiles],modifiedFileFingerprints:generation.modifiedFileFingerprints.map((fingerprint2)=>({...fingerprint2})),createdAt:generation.createdAt,readyAt:generation.readyAt??input.now??Date.now(),consumedAt:input.now??Date.now()};ownershipHistory.set(reviewerScopeOwnershipKey(tombstone.taskId,tombstone.coderCallID,tombstone.generation,tombstone.sessionIncarnation),tombstone)}return generations.delete(key2),cloneReviewerScopeGeneration(generation)}function getReviewerScopeOwnershipHistory(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return[];let{ownershipHistory}=ensureReviewerScopeGenerationState(session);return[...ownershipHistory.values()].map(cloneReviewerScopeOwnershipTombstone)}function peekReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return null;sweepReviewerScopeGenerations(session,input.now??Date.now());let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.values()].filter((entry)=>entry.taskId===input.taskId&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");return matches.length===1?cloneReviewerScopeGeneration(matches[0]):null}function discardReviewerScopeGenerationClaim(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.reviewerCallID===input.reviewerCallID&&entry.status==="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function reviewerScopeGenerationHasDeclaredOverlap(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),declared=new Set(input.declaredFiles);return[...generations.values()].some((entry)=>entry.status==="collecting"&&(entry.taskId!==input.taskId||entry.coderCallID!==input.coderCallID)&&entry.declaredFiles.some((file2)=>declared.has(file2)))}function discardReviewerScopeGenerationForCoderCall(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{generations}=ensureReviewerScopeGenerationState(session),matches=[...generations.entries()].filter(([,entry])=>(input.taskId===void 0||entry.taskId===input.taskId)&&entry.coderCallID===input.coderCallID&&entry.status!=="claimed");if(matches.length!==1)return!1;return generations.delete(matches[0][0]),!0}function isReviewerScopeGenerationCurrent(input){let session=swarmState.agentSessions.get(input.parentSessionID);if(!session)return!1;let{incarnation,latestByTask}=ensureReviewerScopeGenerationState(session),latest=latestByTask.get(input.taskId);return incarnation===input.sessionIncarnation&&latest?.generation===input.generation&&latest.coderCallID===input.coderCallID&&latest.sessionIncarnation===input.sessionIncarnation}function sweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){let staleIds=[];for(let[id,session]of swarmState.agentSessions)if(now-session.lastToolCallTime>staleDurationMs){if(directory&&isSnapshotSessionOwnedLocally(id)&&!isSnapshotSessionAuthoritativelyStale(directory,id,staleDurationMs,now))continue;staleIds.push(id)}for(let id of staleIds){if(directory&&isSnapshotSessionOwnedLocally(id)){try{deleteSnapshotSessionRows(directory,id,"stale")}catch(error49){warn("[state] durable stale-session teardown failed:",error49 instanceof Error?error49.message:String(error49))}try{clearOverrideForSession(directory,id)}catch(error49){warn("[state] durable stale-session override teardown failed:",error49 instanceof Error?error49.message:String(error49))}}releaseSnapshotSessionOwnership(id),swarmState.agentSessions.delete(id),swarmState.delegationChains.delete(id),swarmState.activeAgent.delete(id)}return staleIds}function maybeSweepStaleSessions(staleDurationMs=STALE_SESSION_TTL_MS,now=Date.now(),directory){if(now-_lastIdleSweepAtMs<IDLE_SWEEP_COOLDOWN_MS)return[];return _lastIdleSweepAtMs=now,sweepStaleSessions(staleDurationMs,now,directory)}function startAgentSession(sessionId,agentName,staleDurationMs=STALE_SESSION_TTL_MS,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let owningProjectKey=directory?hydrationProjectKey(directory):void 0,hydrationStamp=owningProjectKey?nextSessionHydrationStamp(owningProjectKey):void 0;sweepStaleSessions(staleDurationMs,now,directory);let sessionState={agentName,lastToolCallTime:now,lastAgentEventTime:now,delegationActive:!1,activeInvocationId:0,lastInvocationIdByAgent:{},windows:{},nonTransientCircuit:createNonTransientCircuitState(agentName,0),pendingToolExecutions:new Map,lastCompactionHint:0,architectWriteCount:0,lastCoderDelegationTaskId:null,currentTaskId:null,gateLog:new Map,reviewerCallCount:new Map,lastGateFailure:null,partialGateWarningsIssuedForTask:new Set,completionGateWarnedForTask:new Set,selfFixAttempted:!1,selfCodingWarnedAtCount:0,catastrophicPhaseWarnings:new Set,lastPhaseCompleteTimestamp:0,lastPhaseCompletePhase:0,phaseAgentsDispatched:new Set,lastCompletedPhaseAgentsDispatched:new Set,qaSkipCount:0,qaSkipTaskIds:[],taskWorkflowStates:new Map,taskWorkflowCache:new Map,stageBCompletion:new Map,stageBRouteEvidence:new Map,stageBRouteRequiredTasks:new Set,taskCouncilApproved:new Map,taskCouncilWorkflowGeneration:new Map,pendingCouncilRequirements:new Map,lastGateOutcome:null,declaredCoderScope:null,lastScopeViolation:null,scopeViolationDetected:!1,modifiedFilesByTask:new Map,modifiedFilesThisCoderTask:[],reviewerScopeGenerations:new Map,reviewerScopeGenerationCounter:0,reviewerScopeIncarnation:randomUUID13(),reviewerScopeLatestGenerationByTask:new Map,reviewerScopeOwnershipHistory:new Map,turboMode:!1,turboStrategy:void 0,leanTurboActive:!1,leanTurboCurrentPhase:void 0,maxConcurrencyOverride:void 0,epicModeActive:!1,qaGateSessionOverrides:{},fullAutoMode:!1,fullAutoInteractionCount:0,fullAutoDeadlockCount:0,fullAutoLastQuestionHash:null,model_fallback_index:0,modelFallbackExhausted:!1,coderRevisions:0,revisionLimitHit:!1,loopDetectionWindow:[],pendingAdvisoryMessages:[],sessionRehydratedAt:0,owningProjectKey,hydrationStamp,prmPatternCounts:new Map,prmEscalationLevel:0,prmLastPatternDetected:null,prmTrajectoryStep:0,prmHardStopPending:!1,prmHardStopInjectPending:!1,prmInjectedAdvisoryKeys:new Set,prmStruckEpisodes:new Map,prmLadderCounts:new Map,prmEpisodes:new Map,prmEpisodeGeneration:0,executionEpisodeArmed:!1,prSubscriptions:new Map};if(swarmState.agentSessions.set(sessionId,sessionState),directory){try{recordSessionStart(directory,now)}catch{}queueMicrotask(()=>{maybeSuggestWorktreeLink(directory,sessionId)})}if(telemetry.sessionStarted(sessionId,agentName),swarmState.activeAgent.set(sessionId,agentName),_internals82.applyRehydrationCache(sessionState),directory){let rehydrationPromise;rehydrationPromise=_internals82.rehydrateSessionFromDisk(directory,sessionState).then(async()=>{try{sessionState.prSubscriptions=await rehydratePrSubscriptions(sessionId,directory)}catch(err){warn("[state] PR subscription rehydration failed, starting with empty subscriptions:",err instanceof Error?err.message:String(err))}}).catch((err)=>{warn("[state] Rehydration failed:",err instanceof Error?err.message:String(err))}).finally(()=>{swarmState.pendingRehydrations.delete(rehydrationPromise)}),swarmState.pendingRehydrations.add(rehydrationPromise)}}function endAgentSession(sessionId,directory){if(directory){try{deleteSnapshotSessionRows(directory,sessionId)}catch(error49){warn("[state] durable snapshot session teardown failed:",error49 instanceof Error?error49.message:String(error49))}try{clearOverrideForSession(directory,sessionId)}catch(error49){warn("[state] durable session override teardown failed:",error49 instanceof Error?error49.message:String(error49))}}releaseSnapshotSessionOwnership(sessionId);let removedBindings=clearScopeBindings((binding)=>binding.ownerSessionId===sessionId||binding.parentOwnerSessionId===sessionId);for(let binding of removedBindings)clearScopeBindingFromDisk({directory:binding.workspaceIdentity,binding});swarmState.agentSessions.delete(sessionId),swarmState.activeAgent.delete(sessionId),swarmState.delegationChains.delete(sessionId),clearRealtimeLearningNudgeSession(sessionId),resetSessionQueue(sessionId),resetPrmPatternSupport(sessionId)}function getAgentSession(sessionId){return swarmState.agentSessions.get(sessionId)}function ensureAgentSession(sessionId,agentName,directory){let now=Date.now();claimSnapshotSessionOwnership(sessionId,!0);let session=swarmState.agentSessions.get(sessionId);if(session){if(agentName&&agentName!==session.agentName){let oldName=session.agentName;if(session.agentName=agentName,telemetry.agentActivated(sessionId,agentName,oldName),session.delegationActive=!1,session.lastAgentEventTime=now,session.nonTransientCircuit=createNonTransientCircuitState(agentName,0),!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={}}if(!session.windows)session.activeInvocationId=0,session.lastInvocationIdByAgent={},session.windows={};if(session.nonTransientCircuit===void 0)session.nonTransientCircuit=createNonTransientCircuitState(session.agentName,session.activeInvocationId??0);if(session.pendingToolExecutions===void 0)session.pendingToolExecutions=new Map;if(session.lastCompactionHint===void 0)session.lastCompactionHint=0;if(session.architectWriteCount===void 0)session.architectWriteCount=0;if(session.lastCoderDelegationTaskId===void 0)session.lastCoderDelegationTaskId=null;if(session.currentTaskId===void 0)session.currentTaskId=null;if(!session.gateLog)session.gateLog=new Map;if(!session.reviewerCallCount)session.reviewerCallCount=new Map;if(session.lastGateFailure===void 0)session.lastGateFailure=null;if(!session.partialGateWarningsIssuedForTask)session.partialGateWarningsIssuedForTask=new Set;if(!session.completionGateWarnedForTask)session.completionGateWarnedForTask=new Set;if(session.selfFixAttempted===void 0)session.selfFixAttempted=!1;if(session.selfCodingWarnedAtCount===void 0)session.selfCodingWarnedAtCount=0;if(!session.catastrophicPhaseWarnings)session.catastrophicPhaseWarnings=new Set;if(session.lastPhaseCompleteTimestamp===void 0)session.lastPhaseCompleteTimestamp=0;if(session.lastPhaseCompletePhase===void 0)session.lastPhaseCompletePhase=0;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;if(!session.lastCompletedPhaseAgentsDispatched)session.lastCompletedPhaseAgentsDispatched=new Set;if(session.qaSkipCount===void 0)session.qaSkipCount=0;if(!session.qaSkipTaskIds)session.qaSkipTaskIds=[];if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.stageBCompletion)session.stageBCompletion=new Map;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;if(!session.pendingCouncilRequirements)session.pendingCouncilRequirements=new Map;if(session.lastGateOutcome===void 0)session.lastGateOutcome=null;if(session.declaredCoderScope===void 0)session.declaredCoderScope=null;if(session.lastScopeViolation===void 0)session.lastScopeViolation=null;if(!(session.modifiedFilesByTask instanceof Map)){if(session.modifiedFilesByTask=new Map,isValidTaskId2(session.currentTaskId)&&Array.isArray(session.modifiedFilesThisCoderTask)&&session.modifiedFilesThisCoderTask.length>0)session.modifiedFilesByTask.set(session.currentTaskId,[...new Set(session.modifiedFilesThisCoderTask)])}if(projectModifiedFilesForActiveTask(session),!session.reviewerScopeGenerations)session.reviewerScopeGenerations=new Map;if(session.reviewerScopeGenerationCounter===void 0)session.reviewerScopeGenerationCounter=0;if(!session.reviewerScopeIncarnation)session.reviewerScopeIncarnation=randomUUID13();if(!session.reviewerScopeLatestGenerationByTask)session.reviewerScopeLatestGenerationByTask=new Map;if(!session.reviewerScopeOwnershipHistory)session.reviewerScopeOwnershipHistory=new Map;if(session.scopeViolationDetected===void 0)session.scopeViolationDetected=!1;if(session.turboMode===void 0)session.turboMode=!1;if(session.turboStrategy===void 0)session.turboStrategy=void 0;if(session.leanTurboActive===void 0)session.leanTurboActive=!1;if(session.leanTurboCurrentPhase===void 0)session.leanTurboCurrentPhase=void 0;if(session.epicModeActive===void 0)session.epicModeActive=!1;if(session.qaGateSessionOverrides===void 0)session.qaGateSessionOverrides={};if(session.model_fallback_index===void 0)session.model_fallback_index=0;if(session.modelFallbackExhausted===void 0)session.modelFallbackExhausted=!1;if(session.loopDetectionWindow===void 0)session.loopDetectionWindow=[];if(session.pendingAdvisoryMessages===void 0)session.pendingAdvisoryMessages=[];if(session.coderRevisions===void 0)session.coderRevisions=0;if(session.revisionLimitHit===void 0)session.revisionLimitHit=!1;if(session.sessionRehydratedAt===void 0)session.sessionRehydratedAt=0;if(session.prmPatternCounts===void 0)session.prmPatternCounts=new Map;if(session.prmEscalationLevel===void 0)session.prmEscalationLevel=0;if(session.prmLastPatternDetected===void 0)session.prmLastPatternDetected=null;if(session.prmTrajectoryStep===void 0)session.prmTrajectoryStep=0;if(session.prmHardStopPending===void 0)session.prmHardStopPending=!1;if(session.prmHardStopInjectPending===void 0)session.prmHardStopInjectPending=!1;if(!session.prmInjectedAdvisoryKeys)session.prmInjectedAdvisoryKeys=new Set;if(!session.prmStruckEpisodes)session.prmStruckEpisodes=new Map;if(!session.prmLadderCounts)session.prmLadderCounts=new Map;if(session.executionEpisodeArmed===void 0)session.executionEpisodeArmed=!1;if(!session.prSubscriptions)session.prSubscriptions=new Map;return session.lastToolCallTime=now,maybeSweepStaleSessions(STALE_SESSION_TTL_MS,now,directory),session}if(_internals82.startAgentSession(sessionId,agentName??"unknown",7200000,directory),session=swarmState.agentSessions.get(sessionId),!session)throw Error(`Failed to create guardrail session for ${sessionId}`);return session}function recordSessionWorkspaceRoot(sessionId,laneRoot){let trimmed=laneRoot.trim();if(!trimmed)return;let session=swarmState.agentSessions.get(sessionId);if(!session)return;session.workspaceDirectory=trimmed}function resolveSessionWorkspaceDirectory(sessionId,fallbackDirectory){let recorded=swarmState.agentSessions.get(sessionId)?.workspaceDirectory;if(recorded?.trim())return recorded;return fallbackDirectory}function updateAgentEventTime(sessionId){let session=swarmState.agentSessions.get(sessionId);if(session)session.lastAgentEventTime=Date.now()}function beginInvocation(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)throw Error(`Cannot begin invocation: session ${sessionId} does not exist`);let stripped=stripKnownSwarmPrefix(agentName),lastId=session.lastInvocationIdByAgent[stripped]||0;if(lastId>0)clearInvocationActionCircuits(sessionId,lastId),clearPendingTaskModelRoutesForSession(sessionId);let newId=lastId+1;if(session.lastInvocationIdByAgent[stripped]=newId,session.activeInvocationId=newId,session.nonTransientCircuit=createNonTransientCircuitState(stripped,newId),stripped===ORCHESTRATOR_NAME)return null;let now=Date.now(),window2={id:newId,agentName:stripped,startedAtMs:now,toolCalls:0,consecutiveErrors:0,hardLimitHit:!1,lastSuccessTimeMs:now,recentToolCalls:[],warningIssued:!1,warningReason:"",transientRetryCount:0},key2=`${stripped}:${newId}`;return session.windows[key2]=window2,pruneOldWindows(sessionId,86400000,50),window2}function getActiveWindow(sessionId){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let key2=`${stripKnownSwarmPrefix(session.agentName)}:${session.activeInvocationId}`;return session.windows[key2]}function pruneOldWindows(sessionId,maxAgeMs=86400000,maxWindows=50){let session=swarmState.agentSessions.get(sessionId);if(!session||!session.windows)return;let now=Date.now(),toKeep=Object.entries(session.windows).filter(([_,window2])=>now-window2.startedAtMs<maxAgeMs).sort((a,b)=>b[1].startedAtMs-a[1].startedAtMs).slice(0,maxWindows);session.windows=Object.fromEntries(toKeep)}function recordPhaseAgentDispatch(sessionId,agentName){let session=swarmState.agentSessions.get(sessionId);if(!session)return;if(!session.phaseAgentsDispatched)session.phaseAgentsDispatched=new Set;let normalizedName=stripKnownSwarmPrefix(agentName);session.phaseAgentsDispatched.add(normalizedName)}function ensureModifiedFilesByTask(session){if(!(session.modifiedFilesByTask instanceof Map))session.modifiedFilesByTask=new Map;return session.modifiedFilesByTask}function projectModifiedFilesForActiveTask(session){let taskId=session.currentTaskId;session.modifiedFilesThisCoderTask=isValidTaskId2(taskId)&&session.modifiedFilesByTask instanceof Map?[...session.modifiedFilesByTask.get(taskId)??[]]:[]}function ensureModifiedFileTaskSlot(session,taskId){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(entries.has(taskId))return!0;while(entries.size>=MAX_TRACKED_TASK_FILE_ATTRIBUTIONS){let reclaimable=[...entries.keys()].find((candidate)=>candidate!==taskId&&session.taskWorkflowStates?.get(candidate)==="complete");if(!reclaimable)return!1;entries.delete(reclaimable)}return entries.set(taskId,[]),!0}function recordModifiedFilesForTask(session,taskId,files){if(!ensureModifiedFileTaskSlot(session,taskId))return!1;let normalized=[...new Set(files.filter((file2)=>typeof file2==="string"&&file2.length>0))];if(session.modifiedFilesByTask.set(taskId,normalized),session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function recordModifiedFileForTask(session,taskId,file2){if(typeof file2!=="string"||file2.length===0)return!1;let existing=getModifiedFilesForTask(session,taskId);if(existing.includes(file2))return!0;return recordModifiedFilesForTask(session,taskId,[...existing,file2])}function getModifiedFilesForTask(session,taskId){if(!isValidTaskId2(taskId))return[];return[...ensureModifiedFilesByTask(session).get(taskId)??[]]}function resetModifiedFilesForTask(session,taskId,options){if(!isValidTaskId2(taskId))return!1;let entries=ensureModifiedFilesByTask(session);if(options?.remove)entries.delete(taskId);else{if(!ensureModifiedFileTaskSlot(session,taskId))return!1;entries.set(taskId,[])}if(session.currentTaskId===taskId)projectModifiedFilesForActiveTask(session);return!0}function completeModifiedFilesForTask(session,taskId){if(!session.epicModeActive)resetModifiedFilesForTask(session,taskId,{remove:!0})}function isValidTaskId2(taskId){if(taskId===null||taskId===void 0)return!1;if(typeof taskId!=="string")return!1;return taskId.trim().length>0}function ensureTaskWorkflowCache(session){if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;return session.taskWorkflowCache}function updateTaskWorkflowCache(session,taskId,overrides2){let cache2=ensureTaskWorkflowCache(session),existing=cache2.get(taskId);cache2.set(taskId,{generation:overrides2.generation??existing?.generation??0,retryCount:overrides2.retryCount??existing?.retryCount??0,lastOutcome:overrides2.lastOutcome??existing?.lastOutcome??"none",lastTransitionId:overrides2.lastTransitionId??existing?.lastTransitionId??null,updatedAt:overrides2.updatedAt??existing?.updatedAt??""})}function advanceTaskState(session,taskId,newState2,options,councilConfig){if(!isValidTaskId2(taskId))return;if(!session||!(session.taskWorkflowStates instanceof Map))throw Error("INVALID_SESSION: session.taskWorkflowStates must be a Map instance");let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} ${current} → ${newState2}`);if(newState2==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)throw Error(`INVALID_TASK_STATE_TRANSITION: ${taskId} cannot reach complete from ${current} — must pass through tests_run first (or have council APPROVE after pre_check)`)}if(session.taskWorkflowStates.set(taskId,newState2),updateTaskWorkflowCache(session,taskId,{updatedAt:new Date().toISOString()}),newState2==="complete")session.stageBCompletion?.delete(taskId),clearStageBRouteEvidence(session,taskId),clearStageBRouteRequired(session,taskId),completeModifiedFilesForTask(session,taskId);if(options?.emitTelemetry!==!1)telemetry.taskStateChanged(options?.telemetrySessionId??session.agentName,taskId,newState2,current)}function canAdvanceTaskState(session,taskId,newState2,councilConfig){if(!isValidTaskId2(taskId))return!1;if(!session||!(session.taskWorkflowStates instanceof Map))return!1;let current=session.taskWorkflowStates.get(taskId)??"idle",currentIndex=LINEAR_STATE_ORDER.indexOf(current),newIndex=LINEAR_STATE_ORDER.indexOf(newState2);if(currentIndex===-1||newIndex===-1||newIndex<=currentIndex)return!1;if(newState2==="complete"&&current!=="tests_run"){let councilEntry=session.taskCouncilApproved?.get(taskId),effectiveMinimum=councilConfig?.requireAllMembers?5:councilConfig?.minimumMembers??3,councilApproved=councilEntry?.verdict==="APPROVE"&&(councilEntry.quorumSize??0)>=effectiveMinimum,pastPreCheck=currentIndex>=LINEAR_STATE_ORDER.indexOf("pre_check_passed");if(!councilApproved||!pastPreCheck)return!1}return!0}async function advanceTaskStateAndPersist(session,taskId,newState2,_directory2,options,councilConfig){if(newState2==="coder_delegated"||newState2==="complete")throw Error(`TASK_WORKFLOW_CENTRAL_TRANSACTION_REQUIRED: ${taskId} → ${newState2} must use exact-task durable transition APIs`);advanceTaskState(session,taskId,newState2,options,councilConfig)}function getTaskState(session,taskId){if(!isValidTaskId2(taskId))return"idle";if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;return session.taskWorkflowStates.get(taskId)??"idle"}function recordStageBCompletion(session,taskId,agent){if(!isValidTaskId2(taskId))return;if(!session.stageBCompletion)session.stageBCompletion=new Map;let existing=session.stageBCompletion.get(taskId);if(existing)existing.add(agent);else session.stageBCompletion.set(taskId,new Set([agent]))}function reserveStageBRouteEvidence(session,taskId,evidence){if(!isValidTaskId2(taskId))return null;if(!session.stageBRouteEvidence)session.stageBRouteEvidence=new Map;let entries=session.stageBRouteEvidence.get(taskId)??[],dispatchIdentity=(entry)=>{if(!entry.callId||!entry.childSessionId||typeof entry.generation!=="number")return null;return[entry.role,entry.sessionId??"",entry.taskId??"",entry.callId,entry.childSessionId,String(entry.generation)].join("\x00")},incomingDispatchIdentity=dispatchIdentity(evidence),existingIndex=entries.findIndex((entry)=>entry.role===evidence.role&&(incomingDispatchIdentity!==null&&dispatchIdentity(entry)===incomingDispatchIdentity||incomingDispatchIdentity===null&&dispatchIdentity(entry)===null&&entry.identity===evidence.identity));if(existingIndex>=0){let previousEntry=entries[existingIndex],reservedEntry2={...evidence};return entries[existingIndex]=reservedEntry2,session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry2);if(reservedIndex<0)return;entries[reservedIndex]=previousEntry}}if(entries.length>=32)return null;let reservedEntry={...evidence};return entries.push(reservedEntry),session.stageBRouteEvidence.set(taskId,entries),()=>{if(session.stageBRouteEvidence?.get(taskId)!==entries)return;let reservedIndex=entries.indexOf(reservedEntry);if(reservedIndex<0)return;if(entries.splice(reservedIndex,1),entries.length===0)session.stageBRouteEvidence?.delete(taskId)}}function recordStageBRouteEvidence(session,taskId,evidence){return reserveStageBRouteEvidence(session,taskId,evidence)!==null}function getStageBRouteEvidence(session,taskId){return(session.stageBRouteEvidence?.get(taskId)??[]).map((entry)=>({...entry}))}function clearStageBRouteEvidence(session,taskId){session.stageBRouteEvidence?.delete(taskId)}function markStageBRouteRequired(session,taskId){if(!session.stageBRouteRequiredTasks)session.stageBRouteRequiredTasks=new Set;session.stageBRouteRequiredTasks.add(taskId)}function isStageBRouteRequired(session,taskId){return session.stageBRouteRequiredTasks?.has(taskId)===!0}function clearStageBRouteRequired(session,taskId){session.stageBRouteRequiredTasks?.delete(taskId)}function hasBothStageBCompletions(session,taskId){if(!isValidTaskId2(taskId))return!1;let completions=session.stageBCompletion?.get(taskId);if(!completions)return!1;return completions.has("reviewer")&&completions.has("test_engineer")}async function isCouncilGateActive(directory,council,sessionOverrides={}){let enabled=council?.enabled===!0,plan=null;try{plan=await loadPlanJsonOnly(directory)}catch{plan=null}if(!plan)return!1;let planId=derivePlanId(plan),lookup=null;try{lookup=getProfileLookupForIdentity(directory,plan)}catch(err){let msg=err instanceof Error?err.message:String(err);if(!(msg.includes("SQLITE_CANTOPEN")||msg.includes("ENOENT")))warn(`[isCouncilGateActive] getProfile threw unexpectedly for plan ${planId}: ${msg}. Treating council as inactive.`);lookup=null}if(!lookup||lookup.kind==="missing")return!1;if(lookup.kind==="unbound_legacy")return enabled&&lookup.profile.gates.council_mode===!0;let profile=lookup.profile,councilMode=getEffectiveGates(profile,sessionOverrides).council_mode===!0;if(enabled&&councilMode)return!0;if(enabled!==councilMode&&!_councilDisagreementWarned.has(planId))_councilDisagreementWarned.add(planId),warn(`[delegation-gate] Council mode mismatch for plan ${planId}: pluginConfig.council.enabled=${enabled}, QaGates.council_mode=${councilMode}. Falling back to Stage B (non-council) per-task advancement.`);return!1}function _resetCouncilDisagreementWarnings(){_councilDisagreementWarned.clear()}function planStatusToWorkflowState(status){switch(status){case"in_progress":return"idle";case"completed":return"complete";case"blocked":return"blocked";case"closed":return"closed";default:return"idle"}}function evidenceToWorkflowState(evidence){let snapshot=getTaskWorkflowSnapshot(evidence);return{state:snapshot.state,generation:snapshot.generation,authoritative:snapshot.authoritative,retryCount:snapshot.retryCount,lastOutcome:snapshot.lastOutcome,lastTransitionId:snapshot.lastTransitionId,updatedAt:snapshot.updatedAt}}async function readPlanFromDisk(directory){try{let planPath=path92.join(directory,".swarm","plan.json"),content=await fs57.readFile(planPath,"utf-8"),parsed=JSON.parse(content);return PlanSchema.parse(parsed)}catch{return null}}async function readGateEvidenceFromDisk(directory){let evidenceMap=new Map;try{let evidenceDir=path92.join(directory,".swarm","evidence"),entries=await fs57.readdir(evidenceDir,{withFileTypes:!0});for(let entry of entries){if(!entry.isFile()||!entry.name.endsWith(".json"))continue;let taskId=entry.name.replace(/\.json$/,"");if(!/^\d+\.\d+(\.\d+)*$/.test(taskId))continue;try{let filePath=path92.join(evidenceDir,entry.name),content=await fs57.readFile(filePath,"utf-8"),parsed=parseTaskEvidence(content,taskId);evidenceMap.set(taskId,parsed)}catch{}}}catch{}return evidenceMap}async function buildRehydrationCache(directory){let planTaskStates=new Map,plan=await readPlanFromDisk(directory);if(plan)for(let phase of plan.phases??[])for(let task of phase.tasks??[])planTaskStates.set(task.id,planStatusToWorkflowState(task.status));let evidenceMap=await readGateEvidenceFromDisk(directory),councilConfig;try{councilConfig=loadPluginConfig(directory).council}catch{councilConfig=void 0}setRehydrationCache(hydrationProjectKey(directory),{planTaskStates,evidenceMap,taskIdentityContext:{plan,councilConfig}})}function applyRehydrationCache(session,projectKey){let resolvedKey=projectKey??session.owningProjectKey;if(!resolvedKey)return;let cache2=getRehydrationCache(resolvedKey);if(!cache2)return;if(!session.taskWorkflowStates)session.taskWorkflowStates=new Map;if(!session.taskWorkflowCache)session.taskWorkflowCache=new Map;if(!session.taskCouncilApproved)session.taskCouncilApproved=new Map;let{planTaskStates,evidenceMap,taskIdentityContext}=cache2;for(let[taskId,planState]of planTaskStates){let existingState=session.taskWorkflowStates.get(taskId),existingCache=ensureTaskWorkflowCache(session).get(taskId),evidence=evidenceMap.get(taskId);if(evidence){let derivedWorkflow=evidenceToWorkflowState(evidence);if(derivedWorkflow.authoritative){session.taskWorkflowStates.set(taskId,derivedWorkflow.state),updateTaskWorkflowCache(session,taskId,{generation:derivedWorkflow.generation,retryCount:derivedWorkflow.retryCount,lastOutcome:derivedWorkflow.lastOutcome,lastTransitionId:derivedWorkflow.lastTransitionId,updatedAt:derivedWorkflow.updatedAt});continue}}if((existingCache?.generation??0)>0)continue;if(existingState==null||compareWorkflowStatePrecedence(planState,existingState)>0)session.taskWorkflowStates.set(taskId,planState)}let VALID_COUNCIL_VERDICTS=new Set(["APPROVE","REJECT","CONCERNS"]);for(let[taskId,evidence]of evidenceMap){let council=evidence.gates?.council;if(!council){session.taskCouncilApproved.delete(taskId);continue}let rawIdentityDigest=council.identity_digest;if(typeof rawIdentityDigest!=="string"||!/^[a-f0-9]{64}$/.test(rawIdentityDigest)){session.taskCouncilApproved.delete(taskId);continue}let expectedIdentity=computeCouncilReviewIdentity({level:"task",scope:{kind:"task",taskId},plan:taskIdentityContext.plan,config:taskIdentityContext.councilConfig});if(rawIdentityDigest!==expectedIdentity.identityDigest){session.taskCouncilApproved.delete(taskId);continue}let councilWorkflow=getTaskWorkflowSnapshot(evidence);if(!councilWorkflow.authoritative||council.workflowGeneration!==councilWorkflow.generation||councilWorkflow.state!=="pre_check_passed"){session.taskCouncilApproved.delete(taskId);continue}let rawVerdict=council.verdict;if(!rawVerdict||typeof rawVerdict!=="string")continue;if(!VALID_COUNCIL_VERDICTS.has(rawVerdict))continue;let verdict=rawVerdict,roundNumber=council.roundNumber;if(typeof roundNumber!=="number"||!Number.isFinite(roundNumber))roundNumber=1;let rawQuorumSize=council.quorumSize,quorumSize=typeof rawQuorumSize==="number"&&Number.isFinite(rawQuorumSize)&&rawQuorumSize>=1?rawQuorumSize:1;session.taskCouncilApproved.set(taskId,{verdict,roundNumber,quorumSize})}}async function rehydrateSessionFromDisk(directory,session){await _internals82.buildRehydrationCache(directory),_internals82.applyRehydrationCache(session,hydrationProjectKey(directory))}function hasActiveTurboMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.turboMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0)return!0;return!1}function hasActiveFullAuto(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.fullAutoMode===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.fullAutoMode===!0)return!0;return!1}function getActiveFullAutoSessionID(){let activeId,activeLastToolCall=-1;for(let[id,session]of swarmState.agentSessions){if(session.fullAutoMode!==!0)continue;let lastToolCall=session.lastToolCallTime??0;if(activeId===void 0||lastToolCall>activeLastToolCall)activeId=id,activeLastToolCall=lastToolCall}return activeId}function hasActiveLeanTurbo(sessionID){if(sessionID){let session=swarmState.agentSessions.get(sessionID);return session?.turboMode===!0&&session?.turboStrategy==="lean"&&session?.leanTurboActive===!0}for(let[_sessionId,session]of swarmState.agentSessions)if(session.turboMode===!0&&session.turboStrategy==="lean"&&session.leanTurboActive===!0)return!0;return!1}function hasActiveEpicMode(sessionID){if(sessionID)return swarmState.agentSessions.get(sessionID)?.epicModeActive===!0;for(let[_sessionId,session]of swarmState.agentSessions)if(session.epicModeActive===!0)return!0;return!1}function getResolvedAutoProceed(session,planAutoProceed){return session.autoProceedOverride??planAutoProceed??!1}function setSessionEnvironment(sessionId,profile){swarmState.environmentProfiles.set(sessionId,profile)}function getSessionEnvironment(sessionId){return swarmState.environmentProfiles.get(sessionId)}function ensureSessionEnvironment(sessionId){let existing=swarmState.environmentProfiles.get(sessionId);if(existing)return existing;let profile=detectEnvironmentProfile();return swarmState.environmentProfiles.set(sessionId,profile),Promise.resolve().then(() => (init_telemetry(),exports_telemetry)).then(({telemetry:telemetry2})=>{telemetry2.environmentDetected(sessionId,profile.hostOS,profile.shellFamily,profile.executionMode)}).catch(()=>{}),profile}function setLiveContextWindow(sessionID,tokens,identity){if(!sessionID)return;let map2=swarmState.liveContextWindows,modelID=trimLiveContextIdentity(identity?.modelID),providerID=trimLiveContextIdentity(identity?.providerID),hasIdentity=Boolean(modelID||providerID),existing=map2.get(sessionID);if(!(typeof tokens==="number"&&Number.isFinite(tokens)&&tokens>=1)){if(!hasIdentity)return;if(existing&&liveContextIdentityMatches(existing,{modelID,providerID})&&existing.tokens!==void 0)return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID);return}if(!hasIdentity&&existing&&(existing.modelID||existing.providerID))return;if(map2.has(sessionID))map2.delete(sessionID);map2.set(sessionID,{tokens:Math.floor(tokens),modelID,providerID}),evictOldestLiveContextWindow(map2,sessionID)}function getLiveContextWindow(sessionID,identity){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;if(identity&&!liveContextIdentityMatches(cached2,identity))return;return cached2.tokens}function getLiveContextModelIdentity(sessionID){if(!sessionID)return;let cached2=swarmState.liveContextWindows.get(sessionID);if(!cached2)return;return{modelID:cached2.modelID,providerID:cached2.providerID}}function evictOldestLiveContextWindow(map2,sessionID){if(map2.size<=MAX_TRACKED_CONTEXT_WINDOWS)return;let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}function trimLiveContextIdentity(value){let trimmed=value?.trim();return trimmed?trimmed:void 0}function normalizeLiveContextIdentity(value){return trimLiveContextIdentity(value)?.toLowerCase()??""}function liveContextIdentityMatches(left,right){return normalizeLiveContextIdentity(left.modelID)===normalizeLiveContextIdentity(right.modelID)&&normalizeLiveContextIdentity(left.providerID)===normalizeLiveContextIdentity(right.providerID)}function setSessionBudget(sessionID,pct,tokens){let map2=swarmState.lastBudgetBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{pct,tokens}),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function setFinalPromptPressure(sessionID,snapshot){let map2=swarmState.finalPromptPressureBySession;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,snapshot),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getFinalPromptPressure(sessionID){if(!sessionID)return;return swarmState.finalPromptPressureBySession.get(sessionID)}function setFinalAccountingWarningBand(sessionID,band){let map2=swarmState.finalAccountingWarningBandsBySession,entry=map2.get(sessionID)??{warn:!1,critical:!1};if(map2.has(sessionID))map2.delete(sessionID);if(band==="critical")entry.critical=!0;else entry.warn=!0;if(map2.set(sessionID,entry),map2.size>MAX_TRACKED_BUDGET_SESSIONS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function getFinalAccountingWarningBand(sessionID,band){if(!sessionID)return!1;let entry=swarmState.finalAccountingWarningBandsBySession.get(sessionID);if(!entry)return!1;return band==="critical"?entry.critical:entry.warn}function clearFinalAccountingWarningBands(){swarmState.finalAccountingWarningBandsBySession.clear()}function getSessionBudgetPct(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.pct??0}function getSessionBudgetTokens(sessionID){if(!sessionID)return 0;return swarmState.lastBudgetBySession.get(sessionID)?.tokens??0}function getDisplayBudget(){let best=null;for(let entry of swarmState.lastBudgetBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function getDisplayFinalPromptPressure(){let best=null;for(let entry of swarmState.finalPromptPressureBySession.values())if(entry.pct>0&&(best===null||entry.pct>best.pct))best=entry;return best}function setCriticalShownIds(sessionID,value){let map2=swarmState.currentCriticalShownIds;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,value),map2.size>MAX_TRACKED_CRITICAL_SHOWN){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}}function clearCriticalShownIds(sessionID){return swarmState.currentCriticalShownIds.delete(sessionID)}function buildGateDenialDirectiveKey(ids){return[...ids].sort().join(",")}function incrementGateDenialCount(sessionID,directiveKey){let map2=swarmState.gateDenialCounts,existing=map2.get(sessionID),count=existing&&existing.directiveKey===directiveKey?existing.count+1:1;if(map2.has(sessionID))map2.delete(sessionID);if(map2.set(sessionID,{count,directiveKey}),map2.size>MAX_TRACKED_GATE_DENIALS){let oldest=map2.keys().next().value;if(oldest!==void 0&&oldest!==sessionID)map2.delete(oldest)}return count}function clearGateDenialCount(sessionID){swarmState.gateDenialCounts.delete(sessionID)}function addKnowledgeAckDedup(key2){let set2=swarmState.knowledgeAckDedup;if(set2.has(key2))return;if(set2.add(key2),set2.size>MAX_TRACKED_KNOWLEDGE_ACKS){let oldest=set2.values().next().value;if(oldest!==void 0)set2.delete(oldest)}}async function rehydratePrSubscriptions(sessionID,directory){let map2=new Map;try{let{listActive:listActive2}=await Promise.resolve().then(() => (init_pr_subscriptions(),exports_pr_subscriptions)),records=await listActive2(directory);for(let record2 of records){if(record2.sessionID!==sessionID)continue;let key2=`${record2.repoFullName}::${record2.prNumber}`;map2.set(key2,{prNumber:record2.prNumber,repoFullName:record2.repoFullName,prUrl:record2.prUrl,lastKnownStatus:record2.mergeableState??"unknown",lastPollTime:record2.lastCheckedAt,errorCount:record2.errorCount,isWatching:record2.isWatching})}}catch(err){warn(`[state] rehydratePrSubscriptions failed for session ${sessionID}: ${err instanceof Error?err.message:String(err)}`)}return map2}var _councilDisagreementWarned,MAX_TRACKED_TASK_FILE_ATTRIBUTIONS=128,LINEAR_STATE_ORDER,_toolAggregates,defaultRunContext,_runContexts,swarmState,STALE_SESSION_TTL_MS=7200000,MAX_REVIEWER_SCOPE_GENERATION_FILES=256,MAX_REVIEWER_SCOPE_GENERATIONS=256,MAX_REVIEWER_SCOPE_OWNERSHIP_HISTORY=256,REVIEWER_SCOPE_GENERATION_TTL_MS,IDLE_SWEEP_COOLDOWN_MS=60000,_lastIdleSweepAtMs=0,MAX_TRACKED_BUDGET_SESSIONS=500,MAX_TRACKED_CRITICAL_SHOWN=500,MAX_TRACKED_KNOWLEDGE_ACKS=5000,MAX_TRACKED_GATE_DENIALS=500,MAX_TRACKED_CONTEXT_WINDOWS=500,_internals82;var init_state2=__esm(()=>{init_constants();init_loader();init_plan_schema();init_schema();init_council_review_identity();init_qa_gate_profile();init_qa_gate_session_override();init_action_circuit();init_gate_evidence();init_delegation_gate();init_realtime_learning_nudge();init_trajectory_step_state();init_candidate_queue();init_prm_pattern_support();init_task_model_routing();init_manager();init_utils3();init_trajectory_store();init_scope_binding();init_scope_persistence();init_injection_budget();init_hydration_ownership();init_session_start_store();init_snapshot_store();init_worktree_link_suggestion();init_telemetry();init_logger();_councilDisagreementWarned=new Set,LINEAR_STATE_ORDER=["idle","coder_delegated","pre_check_passed","reviewer_run","tests_run","complete"];_toolAggregates=new Map,defaultRunContext=new AgentRunContext("default",_toolAggregates),_runContexts=new Map;swarmState={activeToolCalls:defaultRunContext.activeToolCalls,toolAggregates:defaultRunContext.toolAggregates,activeAgent:defaultRunContext.activeAgent,delegationChains:defaultRunContext.delegationChains,pendingEvents:0,opencodeClient:null,curatorInitAgentNames:[],curatorPhaseAgentNames:[],curatorPostmortemAgentNames:[],curatorConsolidationAgentNames:[],skillImproverAgentNames:[],specWriterAgentNames:[],currentCriticalShownIds:new Map,knowledgeAckDedup:new Set,gateDenialCounts:new Map,generatedAgentNames:[],lastBudgetBySession:new Map,finalPromptPressureBySession:new Map,finalAccountingWarningBandsBySession:new Map,liveContextWindows:new Map,agentSessions:defaultRunContext.agentSessions,pendingRehydrations:new Set,fullAutoEnabledInConfig:!1,environmentProfiles:defaultRunContext.environmentProfiles};REVIEWER_SCOPE_GENERATION_TTL_MS=STALE_SESSION_TTL_MS;_internals82={swarmState,resetSwarmState,ensureAgentSession,startAgentSession,getAgentSession,beginInvocation,getActiveWindow,advanceTaskState,getTaskState,hasActiveFullAuto,hasActiveTurboMode,hasActiveLeanTurbo,hasActiveEpicMode,buildRehydrationCache,applyRehydrationCache,rehydrateSessionFromDisk,isCouncilGateActive,defaultRunContext}});async function boundedSessionCall(call,timeoutMs,timeoutLabel,failureLabel,sessionId){let timer;try{await Promise.race([call(),new Promise((_resolve,reject)=>{timer=setTimeout(()=>reject(Error(`${timeoutLabel} after ${timeoutMs}ms`)),Math.max(1,timeoutMs))})])}catch(error49){_internals83.log(`${failureLabel} for ephemeral session`,{sessionId,error:error49 instanceof Error?error49.message:String(error49)})}finally{if(timer)clearTimeout(timer)}}async function boundedAbortEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS){if(typeof session.abort!=="function")return;await _internals83.boundedSessionCall(()=>session.abort({path:{id:sessionId}}),timeoutMs,"ephemeral session abort timed out","ephemeral session abort failed",sessionId)}async function boundedDeleteEphemeralSession(session,sessionId,timeoutMs=DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS){await _internals83.boundedSessionCall(()=>session.delete({path:{id:sessionId}}),timeoutMs,"ephemeral session delete timed out","ephemeral session delete failed",sessionId)}async function teardownEphemeralSession(session,sessionId,options={}){let abortTimeoutMs=options.abortTimeoutMs??DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS,deleteTimeoutMs=options.deleteTimeoutMs??DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS;if(!(options.skipAbort??!1))await _internals83.boundedAbort(session,sessionId,abortTimeoutMs);await _internals83.boundedDelete(session,sessionId,deleteTimeoutMs)}async function sessionExists(session,sessionId,verifyTimeoutMs){if(typeof session.get!=="function")return!0;try{let body=(await withTimeout(session.get({path:{id:sessionId}}),verifyTimeoutMs,Error(`ephemeral session verify timed out after ${verifyTimeoutMs}ms`)))?.data;if(body===void 0||body===null)return!1;return!0}catch{return!1}}async function teardownEphemeralSessionVerified(session,sessionId,options={}){let verifyTimeoutMs=options.verifyTimeoutMs??DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS,attempts=Math.min(6,Math.max(2,options.maxDeleteAttempts??DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS));if(typeof session.get!=="function")return await teardownEphemeralSession(session,sessionId,options),{ok:!1,sessionId,attempts:1,kind:"ephemeral-session-teardown-unverified",reason:"get-unavailable"};let deleteAttempts=0;for(;;){if(await teardownEphemeralSession(session,sessionId,{...options,skipAbort:deleteAttempts>0?!0:options.skipAbort}),deleteAttempts+=1,!await _internals83.sessionExists(session,sessionId,verifyTimeoutMs))return{ok:!0,sessionId,attempts:deleteAttempts};if(deleteAttempts>=attempts)return{ok:!1,sessionId,attempts:deleteAttempts,kind:"ephemeral-session-teardown-unverified",reason:"session-survived-bounded-retries"}}}var DEFAULT_EPHEMERAL_ABORT_TIMEOUT_MS=5000,DEFAULT_EPHEMERAL_TEARDOWN_DELETE_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_VERIFY_TIMEOUT_MS=2000,DEFAULT_EPHEMERAL_MAX_DELETE_ATTEMPTS=3,_internals83;var init_ephemeral_session_teardown=__esm(()=>{init_logger();init_timeout();_internals83={boundedSessionCall,boundedAbort:boundedAbortEphemeralSession,boundedDelete:boundedDeleteEphemeralSession,sessionExists,log}});var init_worktree=__esm(()=>{init_core3();init_merge2()});function verifyReviewerScopeGenerationMergeBack(input){try{let generation=getReviewerScopeGenerationForCoderCall({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,now:input.now});if(!generation||generation.modifiedFiles.length===0)return;if(generation.status!=="collecting"&&generation.status!=="mergeback_pending")return;if(generation.status==="collecting"){if(!markReviewerScopeGenerationMergebackPending({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,at:input.now}))return}let session=ensureAgentSession(input.parentSessionID),deadlineAt=(input.now??Date.now())+REVIEWER_SCOPE_CAPTURE_BATCH_DEADLINE_MS;for(let file2 of generation.modifiedFiles){let stored=generation.modifiedFileFingerprints.find((entry)=>entry.file===file2);if(!stored){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`incomplete fingerprints: ${file2} has no stored capture`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification found no stored fingerprint for ${file2}. ACTION[architect]: re-dispatch the coder for this task`);return}let captured=captureReviewerScopeFileFingerprint(input.primaryDirectory,file2,{deadlineAt});if(captured.kind==="capture_failed"){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`capture ${captured.code} on ${captured.file}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout capture failed for ${captured.file} (${captured.code}). ACTION[architect]: verify the primary checkout, then re-dispatch the reviewer`);return}let capturedFingerprint=reviewerScopeCaptureToFingerprint(captured);if(!capturedFingerprint||!reviewerScopeFileFingerprintsEqual(stored,capturedFingerprint)){settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:`primary bytes differ from lane manifest on ${file2}`,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: primary-checkout bytes differ from the lane manifest on ${file2}; lane evidence retained. ACTION[architect]: resolve the merge conflict or re-dispatch the coder`);return}}let primaryIdentity=canonicalWorkspaceIdentity(input.primaryDirectory);settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!0,primaryWorkspaceIdentity:primaryIdentity??input.primaryDirectory,primaryDirectory:input.primaryDirectory,at:input.now}}),pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_VERIFIED: task ${input.taskId}: primary checkout matches the lane manifest exactly; reviewer dispatch is enabled`)}catch(error49){try{let session=ensureAgentSession(input.parentSessionID);pushAdvisory(session,`REVIEWER_SCOPE_MERGEBACK_MISMATCH: task ${input.taskId}: merge-back verification errored (${String(error49).slice(0,200)}). ACTION[architect]: re-dispatch the reviewer to retry verification`),settleReviewerScopeMergeback({parentSessionID:input.parentSessionID,taskId:input.taskId,coderCallID:input.coderCallID,outcome:{verified:!1,reason:"verification error",at:input.now}})}catch{}}}var init_reviewer_scope_mergeback=__esm(()=>{init_scope_binding();init_state2();init_reviewer_scope_file_fingerprint()});import{createHash as createHash43,randomBytes as randomBytes6}from"node:crypto";import*as fs58 from"node:fs";import*as path93 from"node:path";function nowMs2(input){return input??Date.now()}function sha2565(input){return createHash43("sha256").update(input).digest("hex")}function storePath4(directory){return path93.join(directory,STORE_RELATIVE_PATH)}function journalPath2(directory){return path93.join(directory,JOURNAL_RELATIVE_PATH)}function credentialPath(directory,authorityDigest){return path93.join(directory,CREDENTIAL_DIRECTORY,`${authorityDigest}.json`)}function readAuthorityLockRecord(lockPath){try{let parsed=JSON.parse(fs58.readFileSync(lockPath,"utf8"));if(typeof parsed?.nonce==="string"&&typeof parsed?.acquiredAt==="number"&&Number.isFinite(parsed.acquiredAt)&&typeof parsed?.pid==="number"&&Number.isInteger(parsed.pid))return{nonce:parsed.nonce,acquiredAt:parsed.acquiredAt,pid:parsed.pid}}catch{}return}function writeAuthorityLockRecord(lockPath,record2){try{return fs58.writeFileSync(lockPath,JSON.stringify(record2,null,2),{flag:"wx"}),!0}catch{return!1}}function isProcessAlive2(pid){if(!Number.isSafeInteger(pid)||pid<=0)return!1;try{return process.kill(pid,0),!0}catch{return!1}}function acquireAuthorityLock(directory){let lockPath=path93.join(directory,AUTHORITY_LOCK_RELATIVE_PATH);fs58.mkdirSync(path93.dirname(lockPath),{recursive:!0});let nonce=randomBytes6(16).toString("hex"),acquiredAt=Date.now(),attempt=()=>writeAuthorityLockRecord(lockPath,{nonce,acquiredAt,pid:process.pid});if(!attempt())try{let observed=readAuthorityLockRecord(lockPath);if(!observed)return;if(Date.now()-fs58.statSync(lockPath).mtimeMs>AUTHORITY_LOCK_STALE_MS){if(isProcessAlive2(observed.pid))return;let reread=readAuthorityLockRecord(lockPath);if(reread&&reread.nonce===observed.nonce&&reread.acquiredAt===observed.acquiredAt&&reread.pid===observed.pid){if(fs58.unlinkSync(lockPath),!attempt())return}}}catch{return}let acquired=readAuthorityLockRecord(lockPath);if(!acquired||acquired.nonce!==nonce)return;let released=!1;return()=>{if(released)return;released=!0;try{if(readAuthorityLockRecord(lockPath)?.nonce===nonce)fs58.unlinkSync(lockPath)}catch{}}}function taskKey(parentSessionId,taskId){return`${parentSessionId}::${taskId}`}function stableStringify(value){if(Array.isArray(value))return`[${value.map((item)=>stableStringify(item)).join(",")}]`;if(value&&typeof value==="object")return`{${Object.entries(value).sort(([left],[right])=>left.localeCompare(right)).map(([key2,item])=>`${JSON.stringify(key2)}:${stableStringify(item)}`).join(",")}}`;return JSON.stringify(value)}function digestAuthorityIdentity(input){return sha2565(stableStringify({originalCallID:input.originalCallID,parentSessionId:input.parentSessionId,taskId:input.taskId,reservationId:input.reservationId,generation:input.generation,canonicalBranch:input.canonicalBranch,canonicalPath:input.canonicalPath,laneBranch:input.laneBranch,lanePath:input.lanePath,expectedPrimaryHead:input.expectedPrimaryHead,sourceBaseOid:input.sourceBaseOid,sourceHeadOid:input.sourceHeadOid,targetHeadOid:input.targetHeadOid,strategy:input.strategy,declaredConflictFiles:input.declaredConflictFiles??[]}))}function nonEmpty(value){return typeof value==="string"&&value.length>0&&value.length<=4096}function isHex40(value){return typeof value==="string"&&HEX_40_RE.test(value)}function isOidArray(value){return Array.isArray(value)&&value.length<=4096&&value.every(isHex40)}function isSettlementEvidence(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return isOidArray(candidate.sourceCommitOrder)&&isOidArray(candidate.rewrittenCommitOrder)&&candidate.sourceCommitOrder.length===candidate.rewrittenCommitOrder.length}function isStrategy(value){return value==="merge"||value==="rebase"||value==="cherry-pick"}function isImmutableIdentity(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.originalCallID)&&nonEmpty(candidate.parentSessionId)&&nonEmpty(candidate.taskId)&&nonEmpty(candidate.reservationId)&&typeof candidate.generation==="number"&&Number.isInteger(candidate.generation)&&candidate.generation>0&&nonEmpty(candidate.canonicalBranch)&&nonEmpty(candidate.canonicalPath)&&nonEmpty(candidate.laneBranch)&&nonEmpty(candidate.lanePath)&&isHex40(candidate.expectedPrimaryHead)&&isHex40(candidate.sourceBaseOid)&&isHex40(candidate.sourceHeadOid)&&isHex40(candidate.targetHeadOid)&&isStrategy(candidate.strategy)&&(candidate.declaredConflictFiles===void 0||Array.isArray(candidate.declaredConflictFiles)&&candidate.declaredConflictFiles.every((item)=>nonEmpty(item)))&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function isClaimState(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.claimedAt==="number"&&Number.isFinite(candidate.claimedAt)&&candidate.claimedAt>=0}function isAuthority(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,claimCursor=candidate.claimCursor&&typeof candidate.claimCursor==="object"?candidate.claimCursor:void 0,validStatus=candidate.status==="preserved"||candidate.status==="claimed"||candidate.status==="released"||candidate.status==="finalized";return candidate.schemaVersion===2&&nonEmpty(candidate.authorityDigest)&&isImmutableIdentity(candidate.immutable)&&validStatus&&(candidate.claim===void 0||isClaimState(candidate.claim))&&(claimCursor===void 0||typeof claimCursor.lastClaimRevision==="number"&&Number.isInteger(claimCursor.lastClaimRevision)&&claimCursor.lastClaimRevision>0&&typeof claimCursor.lastAttempt==="number"&&Number.isInteger(claimCursor.lastAttempt)&&claimCursor.lastAttempt>0)&&(candidate.status!=="claimed"||candidate.claim!==void 0)&&(candidate.finalizedAt===void 0||typeof candidate.finalizedAt==="number"&&Number.isFinite(candidate.finalizedAt)&&candidate.finalizedAt>=0)&&(candidate.settlement===void 0||isSettlementEvidence(candidate.settlement))}function isJournalEntry(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value,validState=candidate.state==="PREPARED"||candidate.state==="COMMITTED"||candidate.state==="CLAIM_RENEWED"||candidate.state==="ABORTED"||candidate.state==="RELEASED"||candidate.state==="FINALIZED";return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&validState&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&(candidate.childSessionId===void 0||nonEmpty(candidate.childSessionId))&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&typeof candidate.attempt==="number"&&Number.isInteger(candidate.attempt)&&candidate.attempt>0&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&nonEmpty(candidate.claimTokenDigest)&&typeof candidate.preparedAt==="number"&&Number.isFinite(candidate.preparedAt)&&candidate.preparedAt>=0&&(candidate.credentialInstalledAt===void 0||typeof candidate.credentialInstalledAt==="number"&&Number.isFinite(candidate.credentialInstalledAt)&&candidate.credentialInstalledAt>=0)&&(candidate.committedAt===void 0||typeof candidate.committedAt==="number"&&Number.isFinite(candidate.committedAt)&&candidate.committedAt>=0)&&(candidate.abortedAt===void 0||typeof candidate.abortedAt==="number"&&Number.isFinite(candidate.abortedAt)&&candidate.abortedAt>=0)&&(candidate.reason===void 0||nonEmpty(candidate.reason))}function isCredential(value){if(!value||typeof value!=="object"||Array.isArray(value))return!1;let candidate=value;return candidate.schemaVersion===1&&nonEmpty(candidate.authorityDigest)&&nonEmpty(candidate.claimantCallID)&&nonEmpty(candidate.claimantSessionId)&&nonEmpty(candidate.childSessionId)&&typeof candidate.claimRevision==="number"&&Number.isInteger(candidate.claimRevision)&&candidate.claimRevision>0&&nonEmpty(candidate.rawToken)&&typeof candidate.leaseExpiresAt==="number"&&Number.isFinite(candidate.leaseExpiresAt)&&candidate.leaseExpiresAt>=0&&typeof candidate.createdAt==="number"&&Number.isFinite(candidate.createdAt)&&candidate.createdAt>=0}function rebuildIndex(authorities){let bySessionTask={};for(let authority of[...authorities].sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)){let key2=taskKey(authority.immutable.parentSessionId,authority.immutable.taskId),digests=bySessionTask[key2]??[];digests.push(authority.authorityDigest),bySessionTask[key2]=digests}return{bySessionTask}}function emptyJournal(){return{schemaVersion:1,entries:[]}}function readBoundedJsonFile2(filePath,maxBytes){try{if(fs58.statSync(filePath).size>maxBytes)return{ok:!1,reason:`${path93.basename(filePath)} exceeds the ${maxBytes}-byte safety bound`};let raw=fs58.readFileSync(filePath,"utf8");if(Buffer.byteLength(raw,"utf8")>maxBytes)return{ok:!1,reason:`${path93.basename(filePath)} changed beyond the ${maxBytes}-byte safety bound`};return{ok:!0,value:JSON.parse(raw)}}catch(error49){if(error49.code==="ENOENT")return{ok:!0,value:void 0};return{ok:!1,reason:`${path93.basename(filePath)} is unreadable or malformed: ${error49 instanceof Error?error49.message:String(error49)}`}}}function loadStoreStrict(directory){let loaded=readBoundedJsonFile2(storePath4(directory),MAX_STORE_BYTES);if(!loaded.ok)return{status:"uncertain",reason:loaded.reason};if(loaded.value===void 0)return{status:"ok",authorities:[]};let parsed=loaded.value;if(parsed.schemaVersion===1)return{status:"unsupported-legacy",reason:"worktree recovery v1 records are unsupported for claim mutation"};if(parsed.schemaVersion!==2)return{status:"uncertain",reason:`unknown worktree recovery schema version: ${String(parsed.schemaVersion)}`};if(!Array.isArray(parsed.authorities))return{status:"uncertain",reason:"worktree recovery store does not contain an authorities array"};if(parsed.authorities.length>MAX_STORE_AUTHORITIES)return{status:"uncertain",reason:`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`};for(let authority of parsed.authorities)if(!isAuthority(authority))return{status:"uncertain",reason:"worktree recovery store contains an invalid authority record"};return{status:"ok",authorities:[...parsed.authorities]}}function loadStoreWritable(directory){let scanned=loadStoreStrict(directory);if(scanned.status==="unsupported-legacy")return{ok:!1,code:"unsupported_legacy",reason:scanned.reason};if(scanned.status==="uncertain")return{ok:!1,code:"uncertain_store",reason:scanned.reason};return{schemaVersion:2,authorities:scanned.authorities,index:rebuildIndex(scanned.authorities)}}function loadJournal(directory){let loaded=readBoundedJsonFile2(journalPath2(directory),MAX_JOURNAL_BYTES2);if(!loaded.ok||loaded.value===void 0)return emptyJournal();let parsed=loaded.value;if(parsed.schemaVersion!==1||!Array.isArray(parsed.entries))return emptyJournal();let entries=[];for(let entry of parsed.entries)if(isJournalEntry(entry))entries.push(entry);return{schemaVersion:1,entries:entries.slice(-MAX_JOURNAL_ENTRIES)}}function updateStore(store,authorities){return store.authorities=authorities,store.index=rebuildIndex(authorities),store}function currentClaimMatches(authority,request){if(!authority.claim)return!1;return authority.claim.claimantCallID===request.claimantCallID&&authority.claim.claimRevision===request.claimRevision&&authority.claim.claimTokenDigest===sha2565(request.rawToken)}function latestJournalEntriesByAuthority(journal){let latest=new Map;for(let entry of journal.entries)latest.set(entry.authorityDigest,entry);return[...latest.values()]}function recordJournalEntry(directory,entry){let journal=loadJournal(directory);if(journal.entries.push(entry),journal.entries.length>MAX_JOURNAL_ENTRIES)journal.entries=journal.entries.slice(-MAX_JOURNAL_ENTRIES);return _internals84.writeClaimJournal(journalPath2(directory),journal),journal}function writeCredential(directory,credential){let targetPath=credentialPath(directory,credential.authorityDigest);_internals84.writeCredentialFile(targetPath,credential);try{fs58.chmodSync(targetPath,384)}catch{}return targetPath}function readCredential(directory,authorityDigest){let loaded=readBoundedJsonFile2(credentialPath(directory,authorityDigest),MAX_CREDENTIAL_BYTES);if(!loaded.ok||loaded.value===void 0)return;return isCredential(loaded.value)?loaded.value:void 0}function removeCredentialIfMatch(directory,entry){let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID)try{fs58.unlinkSync(credentialPath(directory,entry.authorityDigest))}catch{}}function baseMutationFailure(code,reason){return{ok:!1,code,reason}}function publishWorktreeRecoveryAuthorityUnlocked(directory,input){let store=loadStoreWritable(directory);if("ok"in store)return store;let immutable={...input,createdAt:nowMs2()};if(!isImmutableIdentity(immutable))return baseMutationFailure("uncertain_store","invalid immutable recovery authority input");let authorityDigest=digestAuthorityIdentity(input),existing=store.authorities.find((authority2)=>authority2.authorityDigest===authorityDigest);if(existing)return{ok:!0,authority:existing};let authority={schemaVersion:2,authorityDigest,immutable,status:"preserved"},nextAuthorities=[...store.authorities,authority];if(nextAuthorities.length>MAX_STORE_AUTHORITIES)return baseMutationFailure("uncertain_store",`worktree recovery authority count exceeds the ${MAX_STORE_AUTHORITIES}-record safety bound`);return _internals84.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"publish"),{ok:!0,authority}}function publishWorktreeRecoveryAuthority(directory,input){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return publishWorktreeRecoveryAuthorityUnlocked(directory,input)}finally{release()}}function scanWorktreeRecoveryAuthoritiesForRecovery(directory){return loadStoreStrict(directory)}function lookupWorktreeRecoveryAuthoritiesByTask(directory,query){let scanned=loadStoreStrict(directory);if(scanned.status!=="ok")return scanned;return{status:"ok",authorities:scanned.authorities.filter((authority)=>authority.immutable.parentSessionId===query.parentSessionId&&authority.immutable.taskId===query.taskId).sort((left,right)=>right.immutable.generation-left.immutable.generation||right.immutable.createdAt-left.immutable.createdAt)}}async function claimWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let authorityIndex=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(authorityIndex===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[authorityIndex];if(authority.status==="finalized")return baseMutationFailure("finalized","finalized worktree recovery authority cannot be claimed again");let currentTime=nowMs2(request.now),previousClaim=authority.claim;if(previousClaim&&previousClaim.leaseExpiresAt>currentTime)return baseMutationFailure("busy","worktree recovery authority is already claimed");if(previousClaim&&previousClaim.leaseExpiresAt<=currentTime){if(!request.revalidateExpiredClaim)return baseMutationFailure("revalidation_required","expired worktree recovery claims require full revalidation before transfer");let verdict=await request.revalidateExpiredClaim({authority,previousClaim});if(!verdict.ok)return baseMutationFailure("revalidation_failed",verdict.reason)}let nextAttempt=(previousClaim?.attempt??authority.claimCursor?.lastAttempt??0)+1,maxAttempts=request.maxAttempts??DEFAULT_MAX_ATTEMPTS;if(nextAttempt>maxAttempts)return baseMutationFailure("retry_cap_exceeded",`worktree recovery claim attempt ${nextAttempt} exceeds the ${maxAttempts}-attempt safety cap`);let nextRevision=(previousClaim?.claimRevision??authority.claimCursor?.lastClaimRevision??0)+1,rawToken=_internals84.generateRawToken(),claimTokenDigest=sha2565(rawToken);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let childSessionId=await request.createChildSession(),refreshedStore=loadStoreWritable(directory);if("ok"in refreshedStore)throw Error(`worktree recovery authority could not be revalidated: ${refreshedStore.reason}`);let refreshedAuthority=refreshedStore.authorities.find((candidate)=>candidate.authorityDigest===request.authorityDigest);if(!refreshedAuthority||stableStringify({status:refreshedAuthority.status,claim:refreshedAuthority.claim,claimCursor:refreshedAuthority.claimCursor,immutable:refreshedAuthority.immutable})!==stableStringify({status:authority.status,claim:authority.claim,claimCursor:authority.claimCursor,immutable:authority.immutable}))throw recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"ABORTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,abortedAt:nowMs2(),reason:"authority changed while child session was being created"}),Error("worktree recovery authority changed while child session was being created");recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime});let credential={schemaVersion:1,authorityDigest:authority.authorityDigest,claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,rawToken,leaseExpiresAt:currentTime+request.leaseMs,createdAt:currentTime},writtenCredentialPath=writeCredential(directory,credential);recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"PREPARED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime});let claimedAuthority={...authority,status:"claimed",claim:{claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,claimedAt:currentTime},claimCursor:{lastClaimRevision:nextRevision,lastAttempt:nextAttempt}},nextAuthorities=[...store.authorities];return nextAuthorities[authorityIndex]=claimedAuthority,_internals84.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-commit"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"COMMITTED",claimantCallID:request.claimantCallID,claimantSessionId:request.claimantSessionId,childSessionId,claimRevision:nextRevision,attempt:nextAttempt,leaseExpiresAt:currentTime+request.leaseMs,claimTokenDigest,preparedAt:currentTime,credentialInstalledAt:currentTime,committedAt:currentTime}),{ok:!0,authority:claimedAuthority,rawToken,credentialPath:writtenCredentialPath}}async function claimWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return await claimWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function renewWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let renewed={...authority,claim:{...authority.claim,leaseExpiresAt:nowMs2(request.now)+request.leaseMs}},nextAuthorities=[...store.authorities];return nextAuthorities[index]=renewed,_internals84.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-renew"),writeCredential(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,rawToken:request.rawToken,leaseExpiresAt:renewed.claim.leaseExpiresAt,createdAt:renewed.claim.claimedAt}),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:renewed.authorityDigest,state:"CLAIM_RENEWED",claimantCallID:renewed.claim.claimantCallID,claimantSessionId:renewed.claim.claimantSessionId,childSessionId:renewed.claim.childSessionId,claimRevision:renewed.claim.claimRevision,attempt:renewed.claim.attempt,leaseExpiresAt:renewed.claim.leaseExpiresAt,claimTokenDigest:renewed.claim.claimTokenDigest,preparedAt:renewed.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim lease renewed"}),{ok:!0,authority:renewed}}function renewWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return renewWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function releaseWorktreeRecoveryClaimUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let released={...authority,status:"preserved",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor},nextAuthorities=[...store.authorities];return nextAuthorities[index]=released,_internals84.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-release"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"RELEASED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim released after preserved settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:released}}function releaseWorktreeRecoveryClaim(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return releaseWorktreeRecoveryClaimUnlocked(directory,request)}finally{release()}}function finalizeWorktreeRecoveryAuthorityUnlocked(directory,request){let store=loadStoreWritable(directory);if("ok"in store)return store;let index=store.authorities.findIndex((authority2)=>authority2.authorityDigest===request.authorityDigest);if(index===-1)return baseMutationFailure("not_found","worktree recovery authority not found");let authority=store.authorities[index];if(!currentClaimMatches(authority,request))return baseMutationFailure("stale_claim","worktree recovery claim is stale or does not match the current claimant");let finalized={...authority,status:"finalized",claim:void 0,claimCursor:authority.claim?{lastClaimRevision:authority.claim.claimRevision,lastAttempt:authority.claim.attempt}:authority.claimCursor,finalizedAt:nowMs2(request.now),settlement:request.settlement},nextAuthorities=[...store.authorities];return nextAuthorities[index]=finalized,_internals84.writeRecoveryStore(storePath4(directory),updateStore(store,nextAuthorities),"claim-finalize"),recordJournalEntry(directory,{schemaVersion:1,authorityDigest:authority.authorityDigest,state:"FINALIZED",claimantCallID:authority.claim.claimantCallID,claimantSessionId:authority.claim.claimantSessionId,childSessionId:authority.claim.childSessionId,claimRevision:authority.claim.claimRevision,attempt:authority.claim.attempt,leaseExpiresAt:authority.claim.leaseExpiresAt,claimTokenDigest:authority.claim.claimTokenDigest,preparedAt:authority.claim.claimedAt,committedAt:nowMs2(request.now),reason:"claim finalized after landed settlement"}),removeCredentialIfMatch(directory,request),{ok:!0,authority:finalized}}function finalizeWorktreeRecoveryAuthority(directory,request){let release=acquireAuthorityLock(directory);if(!release)return baseMutationFailure("busy","worktree recovery authority store is locked");try{return finalizeWorktreeRecoveryAuthorityUnlocked(directory,request)}finally{release()}}function replayWorktreeRecoveryClaimJournalUnlocked(directory,options){let outcomes=[],storeScan=loadStoreStrict(directory),authorities=new Map((storeScan.status==="ok"?storeScan.authorities:[]).map((authority)=>[authority.authorityDigest,authority]));for(let entry of latestJournalEntriesByAuthority(loadJournal(directory))){if(entry.state==="ABORTED"||entry.state==="CLAIM_RENEWED"||entry.state==="RELEASED"||entry.state==="FINALIZED"){outcomes.push({authorityDigest:entry.authorityDigest,outcome:"noop"});continue}if(entry.state==="COMMITTED"){let current2=authorities.get(entry.authorityDigest);if(current2&&!current2.claim&&current2.claimCursor?.lastClaimRevision===entry.claimRevision&&(current2.status==="preserved"||current2.status==="finalized")){recordJournalEntry(directory,{...entry,state:current2.status==="finalized"?"FINALIZED":"RELEASED",reason:"repaired terminal claim journal after interrupted settlement"}),removeCredentialIfMatch(directory,entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"repaired_terminal_claim"});continue}if(current2?.claim&&current2.claim.claimRevision===entry.claimRevision&&current2.claim.claimTokenDigest===entry.claimTokenDigest){let credential2=readCredential(directory,entry.authorityDigest),released=credential2?releaseWorktreeRecoveryClaimUnlocked(directory,{authorityDigest:entry.authorityDigest,claimantCallID:entry.claimantCallID,claimRevision:entry.claimRevision,rawToken:credential2.rawToken}):void 0;outcomes.push({authorityDigest:entry.authorityDigest,outcome:released?.ok?"released_orphaned_committed_claim":"uncertain_committed_without_authority"})}else outcomes.push({authorityDigest:entry.authorityDigest,outcome:"uncertain_committed_without_authority"});continue}let current=authorities.get(entry.authorityDigest);if(current?.claim&&current.claim.claimRevision===entry.claimRevision&&current.claim.claimTokenDigest===entry.claimTokenDigest){recordJournalEntry(directory,{...entry,state:"COMMITTED",committedAt:nowMs2()}),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"committed_claim_stable"});continue}let credential=readCredential(directory,entry.authorityDigest);if(credential&&credential.claimRevision===entry.claimRevision&&credential.claimantCallID===entry.claimantCallID){removeCredentialIfMatch(directory,entry),recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"removed uncommitted credential during replay"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"removed_uncommitted_credential"});continue}recordJournalEntry(directory,{...entry,state:"ABORTED",abortedAt:nowMs2(),reason:"prepared claim never reached credential install or commit"}),options?.onAbortPreparedClaim?.(entry),outcomes.push({authorityDigest:entry.authorityDigest,outcome:"aborted_prepared_claim"})}return outcomes}function replayWorktreeRecoveryClaimJournal(directory,options){let release=acquireAuthorityLock(directory);if(!release)throw Error("worktree recovery authority store is locked");try{return replayWorktreeRecoveryClaimJournalUnlocked(directory,options)}finally{release()}}var STORE_RELATIVE_PATH,JOURNAL_RELATIVE_PATH,CREDENTIAL_DIRECTORY,AUTHORITY_LOCK_RELATIVE_PATH,AUTHORITY_LOCK_STALE_MS=600000,MAX_STORE_BYTES=2097152,MAX_STORE_AUTHORITIES=512,MAX_JOURNAL_BYTES2=2097152,MAX_JOURNAL_ENTRIES=512,MAX_CREDENTIAL_BYTES=16384,DEFAULT_MAX_ATTEMPTS=8,HEX_40_RE,_internals84;var init_worktree_recovery_authority=__esm(()=>{init_atomic_write();STORE_RELATIVE_PATH=path93.join(".swarm","worktree-merge-recovery-v2.json"),JOURNAL_RELATIVE_PATH=path93.join(".swarm","worktree-merge-recovery-v2-journal.json"),CREDENTIAL_DIRECTORY=path93.join(".swarm","worktree-recovery-claims"),AUTHORITY_LOCK_RELATIVE_PATH=path93.join(".swarm","locks","worktree-recovery-authority.lock"),HEX_40_RE=/^[0-9a-f]{40}$/i;_internals84={generateRawToken:()=>randomBytes6(32).toString("hex"),writeRecoveryStore:(targetPath,store,_phase)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(store,null,2))},writeClaimJournal:(targetPath,journal)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(journal,null,2))},writeCredentialFile:(targetPath,credential)=>{atomicWriteSwarmFileSync(targetPath,JSON.stringify(credential,null,2),{mode:384})},getRecoveryStorePath:storePath4,getClaimJournalPath:journalPath2,getCredentialPath:credentialPath,acquireAuthorityLock,readClaimJournal(directory){return loadJournal(directory)},resetForTest(){}}});import*as fs59 from"node:fs";import*as path94 from"node:path";function decodeTagPart(value){if(!value||!/^[A-Za-z0-9_-]+$/.test(value))return null;let decoded=Buffer.from(value,"base64url").toString("utf8");return decoded&&Buffer.from(decoded,"utf8").toString("base64url")===value?decoded:null}async function scanBackgroundWorktreeOwnershipTagsForRecovery(directory){try{fs59.statSync(path94.join(directory,".git"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`Git metadata could not be inspected: ${error49 instanceof Error?error49.message:String(error49)}`}}let proc;try{proc=bunSpawn([resolveGitExecutable(),"-C",directory,"for-each-ref",`--count=${MAX_OWNERSHIP_TAGS+1}`,"--format=%(refname:strip=2)%00%(objectname)","refs/tags/swarm-preserved-owner/"],{stdin:"ignore",stdout:"pipe",stderr:"ignore",timeout:OWNERSHIP_TAG_SCAN_TIMEOUT_MS});let exitCode=await proc.exited;if(exitCode!==0)return{status:"uncertain",reason:`ownership tag scan exited ${exitCode}`};let lines=(await proc.stdout.text()).split(/\r?\n/).map((line)=>line.trim()).filter(Boolean);if(lines.length>MAX_OWNERSHIP_TAGS)return{status:"uncertain",reason:`ownership tag scan exceeded the ${MAX_OWNERSHIP_TAGS}-tag safety bound`};let owners=[];for(let line of lines){let[tag,ref,...extra]=line.split("\x00"),segments=tag?.split("/")??[],sessionId=decodeTagPart(segments[1]??""),laneId=decodeTagPart(segments[2]??""),callDigest=segments[3];if(extra.length>0||segments.length!==4||segments[0]!=="swarm-preserved-owner"||!sessionId||!laneId||!callDigest||!/^[0-9a-f]{12}$/.test(callDigest)||!ref||!/^[0-9a-f]{40,64}$/i.test(ref))return{status:"uncertain",reason:`malformed background ownership tag entry "${tag??""}"`};owners.push({sessionId,laneId,callDigest,ref})}return{status:"ok",owners}}catch(error49){return{status:"uncertain",reason:`ownership tag scan failed: ${error49 instanceof Error?error49.message:String(error49)}`}}finally{try{proc?.kill()}catch{}}}var OWNERSHIP_TAG_SCAN_TIMEOUT_MS=2000,MAX_OWNERSHIP_TAGS=512;var init_worktree_ownership_tag=__esm(()=>{init_bun_compat();init_git_executable()});var exports_worktree_collision_ownership={};__export(exports_worktree_collision_ownership,{inspectStandardWorktreeCollisionOwnership:()=>inspectStandardWorktreeCollisionOwnership,_internals:()=>_internals85});import*as fs60 from"node:fs";function descriptorCoordinateMatch(descriptor,identity){let branchMatches=descriptor.branchName===identity.branchName,pathMatches2=canonicalRootKeyFresh(descriptor.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)return"none";if(!branchMatches||!pathMatches2||descriptor.parentSessionId!==identity.parentSessionId||descriptor.taskId!==identity.taskId)return"uncertain";return"exact"}function isProvenSettled(record2){let settlement=record2.coderSettlement;return settlement?.state==="settled"&&settlement.outcome?.kind==="standard-worktree"&&(settlement.outcome.result==="merged"||settlement.outcome.result==="unchanged")}function classifyRecord(record2,identity,ownerKind){if(!record2.worktree)return null;let coordinates=descriptorCoordinateMatch(record2.worktree,identity);if(coordinates==="none")return null;if(coordinates==="uncertain")return{status:"uncertain",reason:`${ownerKind} background owner has conflicting identity for branch "${identity.branchName}"`};if(isProvenSettled(record2))return null;let lifecycle=record2.coderSettlement?.state==="preserved"?"preserved":"active";return{status:"protected",ownerKind,lifecycle,reason:`${ownerKind} background owner ${record2.correlationId} is ${record2.status}`+(record2.coderSettlement?` with coder settlement ${record2.coderSettlement.state}`:" without a settled workspace outcome")}}async function inspectStandardWorktreeCollisionOwnership(identity){let provisioning=scanWorktreeProvisioningOwnersForRecovery(identity.directory);if(provisioning.status==="uncertain")return provisioning;let now=Date.now();for(let owner of provisioning.owners){if(!(owner.parentSessionId===identity.parentSessionId||owner.worktreeSessionId===identity.parentSessionId))continue;if(owner.schemaVersion===1||owner.taskId===identity.taskId){let leaseIsLive=now-owner.createdAt<=WORKTREE_PROVISIONING_OWNER_LEASE_MS;if(!leaseIsLive)try{_internals85.statSync(identity.worktreePath)}catch(error49){let code=error49.code;if(code!=="ENOENT"&&code!=="ENOTDIR")return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} lane liveness is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`};if(!_internals85.removeWorktreeProvisioningOwner(identity.directory,owner.callID,owner.schemaVersion===3?{reservationId:owner.reservationId,generation:owner.generation,branchName:owner.branchName}:void 0))return{status:"uncertain",reason:`expired provisioning owner ${owner.callID} could not be removed`};continue}return{status:"protected",ownerKind:"provisioning",lifecycle:"active",reason:!leaseIsLive?`provisioning owner ${owner.callID} lease expired, but its exact lane path still exists`:owner.schemaVersion===1?`legacy provisioning owner ${owner.callID} cannot disprove ownership of this same-session lane`:`provisioning owner ${owner.callID} is active for task ${identity.taskId}`}}}let fallback=await scanDelegationFallbacksForRecovery(identity.directory);if(fallback.status==="uncertain")return fallback;for(let artifact of fallback.owners){let classified=classifyRecord(artifact.record,identity,"fallback");if(classified)return classified}let primary=scanDelegationsForRecovery(identity.directory);if(primary.status==="uncertain")return primary;for(let record2 of primary.owners){let classified=classifyRecord(record2,identity,"primary");if(classified)return classified}let tags=await scanBackgroundWorktreeOwnershipTagsForRecovery(identity.directory);if(tags.status==="uncertain")return tags;for(let owner of tags.owners)if(owner.sessionId===identity.parentSessionId&&owner.laneId===identity.taskId)return{status:"protected",ownerKind:"ownership-tag",lifecycle:"preserved",reason:`durable ownership tag ${owner.callDigest} preserves this same-session lane`};let mergeStatus=scanWorktreeMergeFailuresForRecovery(identity.directory);if(mergeStatus.status==="uncertain")return mergeStatus;for(let[,failure]of mergeStatus.failures){let branchMatches=failure.branch===identity.branchName,pathMatches2=typeof failure.worktreePath==="string"&&canonicalRootKeyFresh(failure.worktreePath)===canonicalRootKeyFresh(identity.worktreePath);if(!branchMatches&&!pathMatches2)continue;if(!branchMatches||!pathMatches2)return{status:"uncertain",reason:`merge-status owner has conflicting identity for branch "${identity.branchName}"`};return{status:"protected",ownerKind:"merge-status",lifecycle:"preserved",reason:`merge-status records ${failure.outcome} at stage ${failure.stage}`}}return{status:"unowned"}}var _internals85;var init_worktree_collision_ownership=__esm(()=>{init_pending_delegations();init_canonical_root();init_worktree_merge_status();init_worktree_ownership_tag();init_worktree_provisioning_owner();_internals85={statSync:fs60.statSync,removeWorktreeProvisioningOwner}});var exports_worktree_isolation={};__export(exports_worktree_isolation,{standardWorktreeSerializationSessions:()=>standardWorktreeSerializationSessions,standardWorktreeByCallID:()=>standardWorktreeByCallID,sanitizeWorktreeTaskId:()=>sanitizeWorktreeTaskId,resolveWorktreeIsolationConfig:()=>resolveWorktreeIsolationConfig,resetStandardWorktreeIsolationState:()=>resetStandardWorktreeIsolationState,readLaneEnvFileFromDisk:()=>readLaneEnvFileFromDisk,preserveDirtyWorktreeForCallId:()=>preserveDirtyWorktreeForCallId,preserveDirtyWorktreeAtPath:()=>preserveDirtyWorktreeAtPath,preserveBackgroundWorktreeOwnershipForCallId:()=>preserveBackgroundWorktreeOwnershipForCallId,precreateStandardWorktreeSession:()=>precreateStandardWorktreeSession,preProvisionCollisionCheck:()=>preProvisionCollisionCheck,parseLeanLaneIndex:()=>parseLeanLaneIndex,isLaneOwnedByCurrentSession:()=>isLaneOwnedByCurrentSession,getStandardWorktreeDegradationReason:()=>getStandardWorktreeDegradationReason,finishStandardWorktreeDispatch:()=>finishStandardWorktreeDispatch,computeLaneRuntimeProfile:()=>computeLaneRuntimeProfile,cleanupStandardWorktreeForCallId:()=>cleanupStandardWorktreeForCallId,checkStandardWorktreeSerializationRelease:()=>checkStandardWorktreeSerializationRelease,awaitingMergeByCallID:()=>awaitingMergeByCallID,abortStandardWorktreeDispatch:()=>abortStandardWorktreeDispatch,_internals:()=>_internals79,MAX_TRACKED_STANDARD_WORKTREE_CALLS:()=>MAX_TRACKED_STANDARD_WORKTREE_CALLS});import{createHash as createHash44}from"node:crypto";import*as fs61 from"node:fs/promises";import*as path95 from"node:path";function parseLeanLaneIndex(laneId){let match=/^lane-(\d+)$/.exec(laneId);if(match){let n=parseInt(match[1],10);return Number.isNaN(n)?0:n-1}return 0}function computeLaneRuntimeProfile(runtime,laneIndex,worktreePath){if(!runtime?.enabled)return;let portStride=runtime.port_stride??1,envOverrides={};if(runtime.port_base!==void 0){let portBase=runtime.port_base,port=Math.min(portBase+laneIndex*portStride,65535);envOverrides.PORT=String(port)}if(runtime.env_overrides)Object.assign(envOverrides,runtime.env_overrides);if(runtime.cache_redirects)for(let[envName,basePath]of Object.entries(runtime.cache_redirects)){let laneSuffix=path95.join(basePath,`lane-${laneIndex}`);envOverrides[envName]=laneSuffix}return{laneIndex,worktreePath,envOverrides}}function allocateStandardLaneIndex(parentSessionID){let current=standardWorktreeLaneIndexBySession.get(parentSessionID)??0;return standardWorktreeLaneIndexBySession.set(parentSessionID,current+1),current}async function createSessionWithinBudget(promise2,label,onLateResolve,timeoutMs=_internals79.worktreeSessionCreateTimeoutMs){let settled=new Promise((resolveState)=>{promise2.then((result)=>resolveState({status:"fulfilled",result}),()=>resolveState({status:"rejected"}))});try{return await withTimeout(promise2,timeoutMs,Error(`${label} deadline expired after ${timeoutMs}ms (worktree.session_create_timeout_ms)`))}catch(error49){let teardown=settled.then(async(state2)=>{if(state2.status==="fulfilled")await onLateResolve?.(state2.result)},()=>{}).catch((teardownError)=>{log(`[worktree-isolation] ${label} late-settle teardown failed: ${teardownError instanceof Error?teardownError.message:String(teardownError)}`)});throw await withTimeout(teardown,_internals79.worktreeSessionCreateSettleGraceMs,Error(`${label} settle grace expired`)).catch(()=>{}),error49}}function resolveSessionCreateTimeoutMs(args2){return args2.config?.worktree?.session_create_timeout_ms??_internals79.worktreeSessionCreateTimeoutMs}async function handleStrandedLane(lane){recordDeadLaneReclaim(lane.directory,{lanePath:lane.lanePath,branchName:lane.branchName,parentSessionId:lane.parentSessionID,taskId:lane.taskId,reason:lane.reason});let session=ensureAgentSession(lane.parentSessionID);pushAdvisory(session,`WORKTREE_LANE_STRANDED: lane ${lane.lanePath} could not be removed (${lane.reason}). A child session or system process may hold .swarm/swarm.db (WAL); its DB handle was released via closeProjectDb before this attempt. reclaim scheduled at next start.`)}function rememberStandardWorktreeDispatch(dispatch){standardWorktreeByCallID.set(dispatch.callID,dispatch)}function resolveRecoveryTaskId(input){return input.planTaskId??input.taskId}function toRecoveryStrategy(strategy){return strategy}function hasStandardWorktreeDispatchCapacity(){return standardWorktreeByCallID.size<MAX_TRACKED_STANDARD_WORKTREE_CALLS}function hasInFlightStandardWorktreeDispatch(parentSessionID){for(let dispatch of standardWorktreeByCallID.values())if(dispatch.parentSessionID===parentSessionID)return!0;for(let record2 of awaitingMergeByCallID.values())if(record2.parentSessionID===parentSessionID)return!0;return!1}function handleStandardWorktreeFailure(parentSessionID,policy,message){if(policy==="required")throw new StandardWorktreeLifecycleError(message);if(hasInFlightStandardWorktreeDispatch(parentSessionID))throw new StandardWorktreeLifecycleError(`STANDARD_WORKTREE_ISOLATION_UNSAFE: ${message} Sibling coder task(s) are isolated in worktrees for this session, so dispatching this coder un-isolated in the main tree would risk a merge-back collision. Wait for in-flight coder task(s) to be reviewed and merged, then retry.`);serializeStandardWorktreeDispatches(parentSessionID,message)}function hardStopStandardWorktreeLifecycle(parentSessionID,message){let session=ensureAgentSession(parentSessionID);throw pushAdvisory(session,message),new StandardWorktreeLifecycleError(message)}function serializeStandardWorktreeDispatches(sessionID,message){if(!rememberStandardWorktreeSerializationSession(sessionID)){let session2=ensureAgentSession(sessionID);pushAdvisory(session2,`${message} Serialization tracking is at capacity (256 sessions active); continuing in normal parallel mode.`);return}standardWorktreeDegradationReasonBySession.set(sessionID,{reason:message,at:Date.now()});let session=ensureAgentSession(sessionID);session.maxConcurrencyOverride=1,pushAdvisory(session,`${message} Serializing standard coder dispatches for this session.`)}function getStandardWorktreeDegradationReason(sessionID){return standardWorktreeDegradationReasonBySession.get(sessionID)}function resetStandardWorktreeIsolationState(){standardWorktreeByCallID.clear(),standardWorktreeSerializationSessions.clear(),serializationStateBySessionID.clear(),standardWorktreeDegradationReasonBySession.clear(),awaitingMergeByCallID.clear(),standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession.clear()}function releaseStandardWorktreeSerialization(sessionID){if(!standardWorktreeSerializationSessions.has(sessionID))return!1;standardWorktreeSerializationSessions.delete(sessionID),serializationStateBySessionID.delete(sessionID),standardWorktreeDegradationReasonBySession.delete(sessionID);let session=ensureAgentSession(sessionID);return session.maxConcurrencyOverride=void 0,pushAdvisory(session,`WORKTREE_SERIALIZATION_RELEASED: ${sessionID} regains parallel dispatch eligibility (release-after-dispatches or TTL).`),!0}function checkStandardWorktreeSerializationRelease(sessionID,config2){let state2=serializationStateBySessionID.get(sessionID);if(!state2)return;let count=config2.serialization_release_after_dispatches??5,ttl=config2.serialization_release_after_ms??60000;if(state2.successfulDispatchesSince>=count){releaseStandardWorktreeSerialization(sessionID);return}if(Date.now()-state2.serializedAt>=ttl)releaseStandardWorktreeSerialization(sessionID)}function rememberStandardWorktreeSerializationSession(sessionID){if(standardWorktreeSerializationSessions.size>=MAX_TRACKED_STANDARD_WORKTREE_CALLS){let evicted=!1;for(let key2 of serializationStateBySessionID.keys())if(!hasInFlightStandardWorktreeDispatch(key2)){standardWorktreeSerializationSessions.delete(key2),serializationStateBySessionID.delete(key2),standardWorktreeDegradationReasonBySession.delete(key2),evicted=!0;break}if(!evicted)return log(`[worktree-isolation] serialization set at cap with all sessions active; refusing eviction for ${sessionID}`),!1}if(standardWorktreeSerializationSessions.add(sessionID),!serializationStateBySessionID.has(sessionID))serializationStateBySessionID.set(sessionID,{sessionID,serializedAt:Date.now(),successfulDispatchesSince:0});return!0}function sanitizeWorktreeTaskId(raw){return raw.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64)||"task"}async function preProvisionCollisionCheck(taskId,directory,_sessionId){let proc;try{proc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",directory,"worktree","list","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:WORKTREE_LIST_TIMEOUT_MS})}catch(error49){let detail=`git worktree list could not start in ${directory}: ${error49 instanceof Error?error49.message:String(error49)}`;return log(`[swarm] preProvisionCollisionCheck: ${detail}`),{collision:!1,uncertainty:detail}}let stdout="",stderr="";try{let exitCode=await proc.exited;if(stdout=await proc.stdout.text(),stderr=await proc.stderr.text(),exitCode!==0){if(stderr.toLowerCase().includes("not a git repository"))return{collision:!1};return log(`[swarm] preProvisionCollisionCheck: git worktree list failed (exit ${exitCode}): ${stderr}`),{collision:!1,uncertainty:stderr.trim()||`git worktree list exited ${exitCode}`}}}finally{try{proc.kill()}catch{}}let entries=[],current={path:"",branch:void 0,prunable:!1};for(let rawLine of stdout.split(`
1262
1262
  `)){let line=rawLine.trim();if(line.startsWith("worktree ")){if(current.path)entries.push(current);current={path:line.slice(9),branch:void 0,prunable:!1}}else if(line.startsWith("branch "))current.branch=line.slice(7);else if(line==="prunable"||line.startsWith("prunable "))current.prunable=!0}if(current.path)entries.push(current);for(let entry of entries){if(!entry.branch)continue;if(entry.prunable)continue;let branchName=entry.branch.startsWith("refs/heads/")?entry.branch.slice(11):entry.branch,segments=branchName.split("/");if(segments.length>=4&&segments[0]==="swarm"&&segments[1]==="lane"){if(segments[3]===taskId){let ownerSessionId=segments[2];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}if(segments.length>=3&&segments[0]==="swarm-lane"){if(segments[2]===taskId){let ownerSessionId=segments[1];return{collision:!0,existingBranch:branchName,ownerSessionId,worktreePath:entry.path}}}}return{collision:!1}}function isLaneOwnedByCurrentSession(branchName,expectedSessionId){return _internals35.extractSessionId(branchName)===expectedSessionId}async function inspectStandardWorktreeCollisionOwnership2(identity){return(await Promise.resolve().then(() => (init_worktree_collision_ownership(),exports_worktree_collision_ownership))).inspectStandardWorktreeCollisionOwnership(identity)}async function runRecoveryGit(directory,args2,timeoutMs=15000){let proc;try{proc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",directory,...args2],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:timeoutMs,env:{...process.env,LC_ALL:"C"}});let exitCode=await proc.exited,stdout=await proc.stdout.text(),stderr=await proc.stderr.text();return{exitCode,stdout,stderr}}catch(error49){return{exitCode:1,stdout:"",stderr:error49 instanceof Error?error49.message:String(error49)}}finally{try{proc?.kill()}catch{}}}async function pathExists3(targetPath){try{return await fs61.stat(targetPath),!0}catch{return!1}}async function buildWorktreeRecoveryPublishIdentity(input){let mergeBase=await runRecoveryGit(input.directory,["merge-base",input.provenance.targetHeadBefore,input.provenance.sourceHead]),mergeBaseOid=mergeBase.stdout.trim();if(mergeBase.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(mergeBaseOid))return;let targetHead=await runRecoveryGit(input.directory,["rev-parse","HEAD"]),targetHeadOid=targetHead.stdout.trim();if(targetHead.exitCode!==0||!/^[0-9a-f]{40}$|^[0-9a-f]{64}$/.test(targetHeadOid))return;return{originalCallID:input.dispatch.callID,parentSessionId:input.dispatch.parentSessionID,taskId:input.taskId,reservationId:input.dispatch.reservationId??`worktree:${input.dispatch.parentSessionID}:${input.taskId}`,generation:input.dispatch.generation??1,canonicalBranch:input.dispatch.canonicalBranch??input.dispatch.handle.branchName,canonicalPath:input.dispatch.canonicalPath??input.dispatch.handle.worktreePath,laneBranch:input.dispatch.handle.branchName,lanePath:input.dispatch.handle.worktreePath,expectedPrimaryHead:input.provenance.targetHeadBefore,sourceBaseOid:mergeBaseOid,sourceHeadOid:input.provenance.sourceHead,targetHeadOid,strategy:toRecoveryStrategy(input.provenance.strategy),...input.conflictFiles&&input.conflictFiles.length>0?{declaredConflictFiles:input.conflictFiles}:{}}}async function publishRecoveryAuthorityForSettlement(input){if(input.dispatch.recoveryClaim||!input.provenance)return{ok:!0};let identity=await _internals79.buildWorktreeRecoveryPublishIdentity({directory:input.directory,dispatch:input.dispatch,taskId:input.taskId,provenance:input.provenance,conflictFiles:input.conflictFiles});if(!identity)return{ok:!1,code:"identity_unavailable",reason:"worktree recovery publish identity could not be derived from the merge provenance"};let published=_internals79.publishWorktreeRecoveryAuthority(input.directory,identity);return published.ok?{ok:!0}:{ok:!1,code:published.code,reason:published.reason}}function isExactRecoveryClaimantStillActive(authority){let claim=authority.claim;if(!claim)return!1;if(standardWorktreeByCallID.has(claim.claimantCallID)||awaitingMergeByCallID.has(claim.claimantCallID))return!0;let childSession=swarmState.agentSessions.get(claim.childSessionId);if(!childSession?.workspaceDirectory?.trim())return!1;return sameProjectRoot(childSession.workspaceDirectory,authority.immutable.lanePath)}function describeRecoveryMutationFailure(input){return`recovery claim ${input.action} failed (${input.code}): ${input.reason}`}function maybeSelectRecoverableAuthority(lookup,collision){if(lookup.status!=="ok")return{status:"uncertain",reason:lookup.reason};let authority=lookup.authorities.find((candidate)=>candidate.status!=="finalized"&&candidate.immutable.laneBranch===collision.existingBranch&&candidate.immutable.lanePath===collision.worktreePath);return authority?{status:"match",authority}:{status:"none"}}async function precreateStandardWorktreeSession(args2){let worktreeConfig=resolveWorktreeIsolationConfig(args2.config);if(worktreeConfig.policy==="disabled")return;if(standardWorktreeSerializationSessions.has(args2.parentSessionID)){if(checkStandardWorktreeSerializationRelease(args2.parentSessionID,worktreeConfig),!standardWorktreeSerializationSessions.has(args2.parentSessionID))return}if(!hasStandardWorktreeDispatchCapacity()){if(worktreeConfig.policy==="required")throw Error("STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");serializeStandardWorktreeDispatches(args2.parentSessionID,"STANDARD_WORKTREE_TRACKING_CAP_EXCEEDED: too many standard worktree coder dispatches are already awaiting merge-back.");return}let client=swarmState.opencodeClient;if(!client){handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,"STANDARD_WORKTREE_ISOLATION_UNAVAILABLE: OpenCode SDK client is unavailable; standard parallel coder work cannot be isolated.");return}let laneIndex=allocateStandardLaneIndex(args2.parentSessionID),provisioningOwnerIdentity={reservationId:args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation:Math.max(1,args2.generation??1),branchName:makeWorktreeBranchName(args2.parentSessionID,args2.taskId,{purpose:"lane"})},recoveryLaunch,lifecycleLock=await _internals79.tryAcquireWorktreeLifecycleLock(args2.directory,WORKTREE_LIFECYCLE_LOCK_FILE,"worktree-provisioning",args2.taskId);if(!lifecycleLock.acquired)hardStopStandardWorktreeLifecycle(args2.parentSessionID,"STANDARD_WORKTREE_LIFECYCLE_BUSY: init orphan recovery is active; retry this coder dispatch after recovery completes.");try{let collision=await _internals79.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(collision.uncertainty)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_SCAN_UNCERTAIN: ${collision.uncertainty}. Destructive cleanup and provisioning were blocked.`);if(collision.collision){if(!collision.existingBranch||!collision.worktreePath||!isLaneOwnedByCurrentSession(collision.existingBranch,args2.parentSessionID)){let ownerInfo=collision.ownerSessionId?` owned by session ${collision.ownerSessionId}`:" with uncertain ownership";hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION: task ${args2.taskId} already has a lane on branch ${collision.existingBranch??"unknown"}${ownerInfo}; cleanup and provisioning were blocked.`)}for(let dispatch of _internals79.standardWorktreeByCallID.values())if(dispatch.handle.branchName===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_ACTIVE: branch ${collision.existingBranch} is still tracked by an active standard-worktree dispatch.`);for(let record2 of _internals79.awaitingMergeByCallID.values())if(record2.branch===collision.existingBranch)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`PREPROVISION_COLLISION_AWAITING_MERGE: branch ${collision.existingBranch} is still awaiting merge-back.`);let recoveryCandidate=maybeSelectRecoverableAuthority(_internals79.lookupWorktreeRecoveryAuthoritiesByTask(args2.directory,{parentSessionId:args2.parentSessionID,taskId:resolveRecoveryTaskId(args2)}),collision);if(recoveryCandidate.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_AUTHORITY_UNCERTAIN: ${recoveryCandidate.reason}. Recovery re-dispatch was blocked.`);if(recoveryCandidate.status==="match"){let recoveredChildSessionId="",claimed;try{claimed=await _internals79.claimWorktreeRecoveryAuthority(args2.directory,{authorityDigest:recoveryCandidate.authority.authorityDigest,claimantCallID:args2.callID,claimantSessionId:args2.parentSessionID,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS,createChildSession:async()=>{let createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree recovery lane)`},query:{directory:collision.worktreePath}}),"STANDARD_WORKTREE_RECOVERY_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${lateChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}},resolveSessionCreateTimeoutMs(args2));if(recoveredChildSessionId=createResult.data?.id??"",!recoveredChildSessionId){let createError=createResult.error;throw Error(typeof createError==="string"?createError:JSON.stringify(createError??"missing session id"))}return recoveredChildSessionId},revalidateExpiredClaim:async({authority})=>{if(isExactRecoveryClaimantStillActive(authority))return{ok:!1,reason:"expired recovery claim still belongs to a live claimant session or dispatch"};if(authority.immutable.laneBranch!==collision.existingBranch||authority.immutable.lanePath!==collision.worktreePath)return{ok:!1,reason:"preserved lane coordinates drifted before claim transfer"};try{await fs61.stat(authority.immutable.lanePath)}catch{return{ok:!1,reason:"preserved lane path is no longer live"}}let laneHead=await runRecoveryGit(args2.directory,["rev-parse",`${authority.immutable.laneBranch}^{commit}`]);if(laneHead.exitCode!==0||laneHead.stdout.trim()!==authority.immutable.sourceHeadOid)return{ok:!1,reason:"preserved lane head changed since authority publication"};return{ok:!0}}})}catch(error49){if(_internals79.replayWorktreeRecoveryClaimJournal(args2.directory),recoveredChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,recoveredChildSessionId);if(!verification.ok)pushAdvisory(ensureAgentSession(args2.parentSessionID),`WORKTREE_RECOVERY_CHILD_SESSION_LEAKED: recovery child session ${recoveredChildSessionId} survived verified teardown (${verification.reason}); it holds the lane swarm.db at ${collision.worktreePath}. Retry the dispatch or restart the host to release it.`)}hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_SESSION_CREATE_FAILED: ${error49 instanceof Error?error49.message:String(error49)}. The PREPARED claim was rolled back and recovery re-dispatch was blocked.`)}if(!claimed.ok)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_RECOVERY_CLAIM_FAILED: ${claimed.reason}. The recovery child session ${recoveredChildSessionId} was created but the preserved lane was not reassigned.`);recoveryLaunch={childSessionId:recoveredChildSessionId,worktreePath:collision.worktreePath,branchName:collision.existingBranch,strategy:recoveryCandidate.authority.immutable.strategy,reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,provisioningOwner:{reservationId:recoveryCandidate.authority.immutable.reservationId,generation:recoveryCandidate.authority.immutable.generation,branchName:collision.existingBranch},canonicalBranch:recoveryCandidate.authority.immutable.canonicalBranch,canonicalPath:recoveryCandidate.authority.immutable.canonicalPath,recoveryClaim:{authorityDigest:recoveryCandidate.authority.authorityDigest,claimRevision:claimed.authority.claim?.claimRevision??recoveryCandidate.authority.claimCursor?.lastClaimRevision??1,rawToken:claimed.rawToken,coordinates:{sourceBaseOid:recoveryCandidate.authority.immutable.sourceBaseOid,sourceHeadOid:recoveryCandidate.authority.immutable.sourceHeadOid,targetHeadOid:recoveryCandidate.authority.immutable.targetHeadOid,strategy:recoveryCandidate.authority.immutable.strategy}}}}if(!recoveryLaunch){let ownership=await _internals79.inspectStandardWorktreeCollisionOwnership({directory:args2.directory,parentSessionId:args2.parentSessionID,taskId:args2.taskId,branchName:collision.existingBranch,worktreePath:collision.worktreePath});if(ownership.status==="uncertain")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNERSHIP_UNCERTAIN: ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);if(ownership.status==="protected")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PROTECTED: ${ownership.ownerKind} owner is ${ownership.lifecycle}; ${ownership.reason}. Destructive cleanup and provisioning were blocked.`);let collisionPathExists=!0;try{await fs61.stat(collision.worktreePath)}catch(error49){let code=error49.code;if(code==="ENOENT"||code==="ENOTDIR")collisionPathExists=!1;else hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PATH_STAT_FAILED: ${error49 instanceof Error?error49.message:String(error49)}. Destructive cleanup and provisioning were blocked.`)}if(collisionPathExists){let preserveResult=await _internals79.preserveDirtyWorktreeAtPath(collision.worktreePath,collision.existingBranch,"denied",args2.directory,worktreeConfig.worktree_dir);if(preserveResult.outcome==="preserve-failed")hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: pre-provision collision for task ${args2.taskId} could not be preserved (${preserveResult.error}). Cleanup and provisioning were blocked.`);closeProjectDb(collision.worktreePath);let removeResult=await _internals79.removeWorktree(collision.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir});if("error"in removeResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_REMOVE_FAILED: ${removeResult.error}. Provisioning was blocked.`);let cleanupResult=await _internals79.postMergeCleanup(args2.directory,collision.existingBranch);if("error"in cleanupResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_BRANCH_CLEANUP_FAILED: ${cleanupResult.error}. Provisioning was blocked.`)}else{let pruneResult=await _internals79.pruneStaleWorktreeMetadata(args2.directory);if("error"in pruneResult)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_PRUNE_FAILED: ${pruneResult.error}. Provisioning was blocked without deleting the lane branch.`)}let verification=await _internals79.preProvisionCollisionCheck(args2.taskId,args2.directory,args2.parentSessionID);if(verification.uncertainty||verification.collision)hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_COLLISION_CLEANUP_UNVERIFIED: ${verification.uncertainty??"git still reports the colliding lane after cleanup"}. Provisioning was blocked.`)}}_internals79.recordWorktreeProvisioningOwner(args2.directory,{callID:args2.callID,parentSessionId:args2.parentSessionID,worktreeSessionId:args2.parentSessionID,taskId:args2.taskId,...provisioningOwnerIdentity})}catch(error49){if(error49 instanceof StandardWorktreeLifecycleError)throw error49;hardStopStandardWorktreeLifecycle(args2.parentSessionID,`STANDARD_WORKTREE_OWNER_PERSIST_FAILED: ${error49 instanceof Error?error49.message:String(error49)}.`)}finally{try{await lifecycleLock.lock._release?.()}catch{}}let childSessionId="",handle,mergeStrategy,reservationId,generation,canonicalBranch,canonicalPath,recoveryClaim;if(recoveryLaunch)childSessionId=recoveryLaunch.childSessionId,handle={worktreePath:recoveryLaunch.worktreePath,branchName:recoveryLaunch.branchName,purpose:"lane",id:sanitizeWorktreeTaskId(args2.taskId),sessionId:args2.parentSessionID},mergeStrategy=recoveryLaunch.strategy,reservationId=recoveryLaunch.reservationId,generation=recoveryLaunch.generation,provisioningOwnerIdentity=recoveryLaunch.provisioningOwner,canonicalBranch=recoveryLaunch.canonicalBranch,canonicalPath=recoveryLaunch.canonicalPath,recoveryClaim=recoveryLaunch.recoveryClaim;else{reservationId=args2.reservationId??`foreground:${args2.parentSessionID}:${resolveRecoveryTaskId(args2)}:${args2.callID}`,generation=provisioningOwnerIdentity.generation,canonicalPath=args2.directory;let provisionResult;try{provisionResult=await _internals79.provisionWorktree(args2.directory,args2.taskId,args2.parentSessionID,{purpose:"lane",worktreeDir:worktreeConfig.worktree_dir,mergeStrategy:worktreeConfig.merge_strategy,depsStrategy:worktreeConfig.deps_strategy,scope:args2.scope})}catch(error49){throw _internals79.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity),error49}if("error"in provisionResult){_internals79.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_PROVISION_FAILED: ${provisionResult.error}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}handle=provisionResult,mergeStrategy=worktreeConfig.merge_strategy,recordLiveLaneOwner(args2.directory,{lanePath:handle.worktreePath,branchName:handle.branchName,sessionId:args2.parentSessionID,taskId:args2.taskId})}let originalPrompt=typeof args2.outputArgs.prompt==="string"?args2.outputArgs.prompt:"";args2.outputArgs.prompt=["<worktree_lane_context>",`authoritative_lane_root: ${JSON.stringify(handle.worktreePath)}`,"All FILE declarations and scope-bound edit/write paths must be workspace-relative to authoritative_lane_root.","Remain in authoritative_lane_root: do not change directory into, or edit/write through, the primary checkout or any other worktree.","Example: FILE: src/example.ts means <authoritative_lane_root>/src/example.ts, never <primary-checkout>/src/example.ts.","Do not declare project-root absolute paths; resolve and operate inside this lane root.","</worktree_lane_context>","",originalPrompt].join(`
1263
1263
  `);let laneProfile=computeLaneRuntimeProfile(worktreeConfig.runtime_isolation,laneIndex,handle.worktreePath);if(laneProfile)try{let{writeLaneProfileToDiskReal:writeLaneProfileToDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await writeLaneProfileToDiskReal2(handle.worktreePath,laneProfile.laneIndex,laneProfile.envOverrides)}catch{}if((worktreeConfig.deps_strategy??"skip")==="skip"){let desc=(args2.description??args2.taskId??"").toLowerCase();if(/\btests?\b/.test(desc)||/\bbuild(ing|s)?\b/.test(desc)||/\blint(ing|er)?\b/.test(desc)||/\bchecks?\b/.test(desc)){let session=ensureAgentSession(args2.parentSessionID);pushAdvisory(session,`WORKTREE_DEPS_SKIP: task ${args2.taskId} was provisioned with deps_strategy: 'skip' (default). This task's gates appear to include test/build commands; the lane may lack node_modules. Set worktree.deps_strategy to 'copy' or 'link' (or use a non-worktree lane) if the task requires host dependencies.`)}}if(!recoveryLaunch){let createResult;try{createResult=await createSessionWithinBudget(client.session.create({body:{parentID:args2.parentSessionID,title:`${args2.description??args2.taskId} (worktree lane)`},query:{directory:handle.worktreePath}}),"STANDARD_WORKTREE_SESSION_CREATE",async(result)=>{let lateChildSessionId=result.data?.id;if(lateChildSessionId){let verification=await teardownEphemeralSessionVerified(client.session,lateChildSessionId);if(!verification.ok)await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:`late child session ${lateChildSessionId} survived verified teardown (${verification.reason})`})}},resolveSessionCreateTimeoutMs(args2))}catch(error49){closeProjectDb(handle.worktreePath);let removal=await _internals79.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals79.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${error49 instanceof Error?error49.message:String(error49)}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}if(!createResult?.data?.id){closeProjectDb(handle.worktreePath);let removal=await _internals79.removeWorktree(handle.worktreePath,args2.directory,{force:!0,worktreeDir:worktreeConfig.worktree_dir}).catch((cleanupError)=>({error:cleanupError instanceof Error?cleanupError.message:String(cleanupError)})),removalError=typeof removal==="object"&&removal!==null&&"error"in removal&&typeof removal.error==="string"?removal.error:void 0;if(removalError)log(`[worktree-isolation] session-create failure cleanup could not remove lane ${handle.worktreePath}: ${removalError}`),await handleStrandedLane({directory:args2.directory,parentSessionID:args2.parentSessionID,lanePath:handle.worktreePath,branchName:handle.branchName,taskId:args2.taskId,reason:removalError});_internals79.removeWorktreeProvisioningOwner(args2.directory,args2.callID,provisioningOwnerIdentity);let createError=createResult.error,message=`STANDARD_WORKTREE_SESSION_CREATE_FAILED: ${typeof createError==="string"?createError:JSON.stringify(createError??"missing session id")}.`;handleStandardWorktreeFailure(args2.parentSessionID,worktreeConfig.policy,message);return}childSessionId=createResult.data.id}if(!childSessionId)throw Error("STANDARD_WORKTREE_SESSION_CREATE_FAILED: missing child session id.");args2.outputArgs.task_id=childSessionId,ensureAgentSession(childSessionId,"coder",handle.worktreePath),recordSessionWorkspaceRoot(childSessionId,handle.worktreePath),rememberStandardWorktreeDispatch({callID:args2.callID,parentSessionID:args2.parentSessionID,taskId:args2.taskId,planTaskId:args2.planTaskId,reservationId,generation,provisioningOwner:provisioningOwnerIdentity,canonicalBranch,canonicalPath,handle,mergeStrategy,recoveryClaim,laneIndex,worktree_dir:worktreeConfig.worktree_dir})}async function preserveBackgroundWorktreeOwnershipForCallId(callID){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch)return{outcome:"not-found"};let refProc;try{refProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let ref="";try{let exitCode=await refProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await refProc.stderr.text()||`git rev-parse exited ${exitCode}`};ref=(await refProc.stdout.text()).trim()}finally{try{refProc.kill()}catch{}}if(!ref)return{outcome:"preserve-failed",error:"git rev-parse returned empty"};let session=Buffer.from(dispatch.handle.sessionId,"utf8").toString("base64url"),lane=Buffer.from(dispatch.handle.id,"utf8").toString("base64url"),callDigest=createHash44("sha256").update(callID).digest("hex").slice(0,12),tag=`swarm-preserved-owner/${session}/${lane}/${callDigest}`,tagProc;try{tagProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",dispatch.handle.worktreePath,"tag",tag,ref],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let exitCode=await tagProc.exited;if(exitCode!==0)return{outcome:"preserve-failed",error:await tagProc.stderr.text()||`git tag exited ${exitCode}`}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",tag,ref}}async function preserveDirtyWorktreeForCallId(callID,reason,_directory2,_worktree_dir){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{outcome:"clean",preserved:!1};worktreePath=awaiting.worktreePath,parentSessionID=awaiting.parentSessionID}let statusProc;try{statusProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeForCallId: git status failed for ${callID}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git add failed for ${callID}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedCallID=callID.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for callID ${sanitizedCallID} at ${isoDate}`,commitProc;try{commitProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git commit failed for ${callID}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git rev-parse failed for ${callID}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-${sanitizedCallID}-${shortHash}`,tagProc;try{tagProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeForCallId: git tag failed for ${callID}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_PRESERVED: dispatch ${callID} dirty work preserved as commit ${commitHash} (tag: ${tagName}; reason: ${reason}); worktree will be cleaned.`),{outcome:"preserved",preserved:!0,ref:commitHash}}async function preserveDirtyWorktreeAtPath(worktreePath,branchName,reason,_directory2,_worktree_dir){let statusProc;try{statusProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"status","--porcelain"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git status could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let statusStdout="",statusStderr="";try{let exitCode=await statusProc.exited;if(statusStdout=await statusProc.stdout.text(),statusStderr=await statusProc.stderr.text(),exitCode!==0)return log(`[swarm] preserveDirtyWorktreeAtPath: git status failed for ${worktreePath}: ${statusStderr}`),{outcome:"preserve-failed",preserved:!1,error:`git status failed: ${statusStderr||`exit ${exitCode}`}`}}finally{try{statusProc.kill()}catch{}}if(statusStdout.trim()==="")return{outcome:"clean",preserved:!1};let addProc;try{addProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"add","-A"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git add could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let addExit=await addProc.exited;if(addExit!==0){let addErr=await addProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git add failed for ${worktreePath}: ${addErr}`),{outcome:"preserve-failed",preserved:!1,error:`git add failed: ${addErr||`exit ${addExit}`}`}}}finally{try{addProc.kill()}catch{}}let isoDate=new Date().toISOString(),sanitizedPath=worktreePath.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),sanitizedBranch=branchName.replace(/[^A-Za-z0-9._-]/g,"-").slice(0,64),commitMessage=`swarm-preserved: ${reason} for worktree ${sanitizedPath} at ${isoDate}`,commitProc;try{commitProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"commit","-m",commitMessage],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git commit could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}let commitHash="";try{let commitExit=await commitProc.exited;if(commitExit!==0){let commitErr=await commitProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git commit failed for ${worktreePath}: ${commitErr}`),{outcome:"preserve-failed",preserved:!1,error:`git commit failed: ${commitErr||`exit ${commitExit}`}`}}}finally{try{commitProc.kill()}catch{}}let hashProc;try{hashProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"rev-parse","HEAD"],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git rev-parse could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let hashExit=await hashProc.exited;if(hashExit!==0){let hashErr=await hashProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git rev-parse failed for ${worktreePath}: ${hashErr}`),{outcome:"preserve-failed",preserved:!1,error:`git rev-parse failed: ${hashErr||`exit ${hashExit}`}`}}commitHash=(await hashProc.stdout.text()).trim()}finally{try{hashProc.kill()}catch{}}if(!commitHash)return{outcome:"preserve-failed",preserved:!1,error:"git rev-parse returned empty hash"};let shortHash=commitHash.slice(0,8),tagName=`swarm-preserved-worktree-${sanitizedBranch}-${shortHash}`,tagProc;try{tagProc=_internals79.bunSpawn([_internals79.resolveGitExecutable(),"-C",worktreePath,"tag",tagName],{stdin:"ignore",stdout:"pipe",stderr:"pipe",timeout:PRESERVE_COMMIT_TIMEOUT_MS})}catch(error49){return{outcome:"preserve-failed",preserved:!1,error:`git tag could not start: ${error49 instanceof Error?error49.message:String(error49)}`}}try{let tagExit=await tagProc.exited;if(tagExit!==0){let tagErr=await tagProc.stderr.text();return log(`[swarm] preserveDirtyWorktreeAtPath: git tag failed for ${worktreePath}: ${tagErr}`),{outcome:"preserve-failed",preserved:!1,error:`git tag failed: ${tagErr||`exit ${tagExit}`}`}}}finally{try{tagProc.kill()}catch{}}return{outcome:"preserved",preserved:!0,ref:commitHash}}async function cleanupStandardWorktreeForCallId(callID,reason,directory,worktree_dir,options){let dispatch=standardWorktreeByCallID.get(callID),worktreePath,branchName,parentSessionID;if(dispatch)worktreePath=dispatch.handle.worktreePath,branchName=dispatch.handle.branchName,parentSessionID=dispatch.parentSessionID;else{let awaiting=awaitingMergeByCallID.get(callID);if(!awaiting)return{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1};worktreePath=awaiting.worktreePath,branchName=awaiting.branch,parentSessionID=awaiting.parentSessionID}if(dispatch?.recoveryClaim&&(reason==="denied"||reason==="cancelled")){let renewResult=_internals79.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(!renewResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"renew",code:renewResult.code,reason:renewResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}let releaseResult=_internals79.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:callID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(!releaseResult.ok){let message=`STANDARD_WORKTREE_RECOVERY_ABORT_RELEASE_FAILED: dispatch ${callID} preserved lane ${worktreePath} (${branchName}) after ${reason}, but ${describeRecoveryMutationFailure({action:"release",code:releaseResult.code,reason:releaseResult.reason})}. No tracking teardown was performed.`,session3=ensureAgentSession(parentSessionID);throw pushAdvisory(session3,message),Error(message)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_RECOVERY_ABORT_PRESERVED: dispatch ${callID} released its recovery claim and preserved lane ${worktreePath} (${branchName}) after ${reason}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!0}}let preserveResult;if(reason==="denied"||reason==="cancelled"){try{preserveResult=await _internals79.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: preserveDirtyWorktreeForCallId threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}if(preserveResult.outcome==="clean")try{preserveResult=await _internals79.preserveDirtyWorktreeForCallId(callID,reason,directory,worktree_dir)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: final preservation check threw for ${callID}: ${err}`),preserveResult={outcome:"preserve-failed",preserved:!1,error:String(err)}}}if(preserveResult&&preserveResult.outcome==="preserve-failed"){standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session2=ensureAgentSession(parentSessionID);return pushAdvisory(session2,`STANDARD_WORKTREE_PRESERVATION_FAILED_ABORT_CLEANUP: dispatch ${callID} has dirty uncommitted work but preservation failed (${preserveResult.error}). Cleanup aborted to protect uncommitted work. Investigate and resolve manually. Worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree:!1,cleanedBranch:!1,preservedRecoveryLane:!1}}let removedWorktree=!1;try{closeProjectDb(worktreePath);let result=await _internals79.removeWorktree(worktreePath,directory,{force:!0,worktreeDir:worktree_dir});if(!("error"in result))removedWorktree=!0;else if(result.error.includes("is not a working tree")&&await pathExists3(worktreePath)&&isPathUnderSwarmWorktreeBase(worktreePath,directory,worktree_dir?[worktree_dir]:[]))try{await fs61.rm(worktreePath,{recursive:!0,force:!0}),removedWorktree=!await pathExists3(worktreePath)}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: residual directory cleanup failed for ${callID}: ${err}`)}}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: removeWorktree failed for ${callID}: ${err}`)}let cleanedBranch=!1;if(options?.retainBranch){let retainedSession=ensureAgentSession(parentSessionID);pushAdvisory(retainedSession,`STANDARD_WORKTREE_BRANCH_RETAINED: dispatch ${callID} removed worktree ${worktreePath} but retained branch ${branchName} (unstaged landing); the branch is the recovery backup until the landed changes are committed.`)}else try{cleanedBranch=!("error"in await _internals79.postMergeCleanup(directory,branchName))}catch(err){log(`[swarm] cleanupStandardWorktreeForCallId: postMergeCleanup failed for ${callID}: ${err}`)}standardWorktreeByCallID.delete(callID),awaitingMergeByCallID.delete(callID);let session=ensureAgentSession(parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_CLEANUP: dispatch ${callID} cleaned up (reason: ${reason}); worktree=${worktreePath}; branch=${branchName}.`),{removedWorktree,cleanedBranch,preservedRecoveryLane:!1}}async function abortStandardWorktreeDispatch(callID,reason,directory){let dispatch=standardWorktreeByCallID.get(callID);if(!dispatch){let session=ensureAgentSession("unknown");pushAdvisory(session,`STANDARD_WORKTREE_ABORT_NOOP: dispatch ${callID} has no tracked worktree to abort (reason: ${reason}).`);return}await cleanupStandardWorktreeForCallId(callID,reason,directory,dispatch.worktree_dir)}async function finishStandardWorktreeDispatch(directory,dispatch,config2,callID,settlement={}){let wtConfig=config2?resolveWorktreeIsolationConfig(config2):DEFAULT_WORKTREE_ISOLATION_CONFIG,resolvedCallID=callID??dispatch.callID,run=async()=>{let statusKey=dispatch.planTaskId??dispatch.taskId,failRecoverySettlement=(stage,message,provenance)=>{recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage,message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_RECOVERY_MUTATION_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage,message,provenance}},renewRecoveryClaimLease=(phase,provenance)=>{if(!dispatch.recoveryClaim)return;let renewed=_internals79.renewWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,leaseMs:WORKTREE_RECOVERY_CLAIM_LEASE_MS});if(renewed.ok)return;return failRecoverySettlement("recovery-claim-renew",`The live recovery lane could not extend its lease ${phase}; ${describeRecoveryMutationFailure({action:"renew",code:renewed.code,reason:renewed.reason})}`,provenance)},releaseRecoveryClaim=(provenance)=>{if(!dispatch.recoveryClaim)return;let released=_internals79.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken});if(released.ok)return;return failRecoverySettlement("recovery-claim-release",`The preserved recovery lane could not release its exact claim after settlement; ${describeRecoveryMutationFailure({action:"release",code:released.code,reason:released.reason})}`,provenance)},publishRecoveryAuthority=async(provenance,conflictFiles)=>{let published=await publishRecoveryAuthorityForSettlement({directory,dispatch,taskId:statusKey,provenance,conflictFiles});if(published.ok)return;return failRecoverySettlement("recovery-authority-publish",`The preserved original lane could not publish recoverable authority; ${describeRecoveryMutationFailure({action:"publish",code:published.code,reason:published.reason})}`,provenance)},preMergeRenewFailure=renewRecoveryClaimLease("before merge-back");if(preMergeRenewFailure)return preMergeRenewFailure;let mergeResult=await(async()=>{if(!dispatch.recoveryClaim)return _internals79.attemptMergeBackFromDirty(dispatch.handle.worktreePath,dispatch.handle.branchName,directory,getMergeStrategy({merge_strategy:dispatch.mergeStrategy}),{operationId:settlement.operationId,resume:settlement.resume,onBeforeMerge:settlement.onBeforeMerge,commitLanding:settlement.commitLanding});let coordinates=dispatch.recoveryClaim.coordinates;if(!coordinates)return{failed:!0,stage:"recovery-coordinates",message:"Claimed recovery lane is missing immutable Git coordinates"};let provenance={operationId:settlement.operationId??`recovery:${dispatch.recoveryClaim.authorityDigest}`,sourceHead:coordinates.sourceHeadOid,targetHeadBefore:coordinates.targetHeadOid,branchName:dispatch.handle.branchName,strategy:coordinates.strategy};if(settlement.onBeforeMerge)await settlement.onBeforeMerge(provenance);let recovered=await _internals79.recoverMergeBackFromImmutableCoordinates(directory,coordinates);if("merged"in recovered&&recovered.merged){if(recovered.sourceCommitOrder&&recovered.rewrittenCommitOrder)dispatch.recoveryClaim.settlement={sourceCommitOrder:recovered.sourceCommitOrder,rewrittenCommitOrder:recovered.rewrittenCommitOrder};return{merged:!0,strategy:recovered.strategy,autoCommitted:!1,cleaned:!0,reconciled:!1,provenance}}if("conflict"in recovered&&recovered.conflict)return{partial:!0,stage:"conflict",autoCommitted:!1,cleaned:!0,message:recovered.message,conflictFiles:recovered.files,provenance};return{failed:!0,stage:"recovery",message:"error"in recovered?recovered.error:"Immutable recovery returned an unexpected result",provenance}})();if("merged"in mergeResult&&mergeResult.merged){let mergedSettlement={outcome:"merged",strategy:mergeResult.strategy,autoCommitted:mergeResult.autoCommitted??!1,cleaned:mergeResult.cleaned??!1,reconciled:mergeResult.reconciled??!1,provenance:mergeResult.provenance};if(settlement.onMerged)try{await settlement.onMerged(mergedSettlement)}catch(error49){let failedSettlement={outcome:"failed",stage:"settlement-persist",message:`Git merge-back succeeded but settlement persistence failed: ${String(error49)}`,provenance:mergeResult.provenance},publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)failedSettlement.message=`${failedSettlement.message} ${publishFailure.message}`;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)failedSettlement.message=`${failedSettlement.message} ${releaseFailure.message}`;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:failedSettlement.stage,message:failedSettlement.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_PERSIST_FAILED: task ${dispatch.taskId} landed in ${directory}, but settlement persistence failed; worktree and branch preserved at ${dispatch.handle.worktreePath} (${dispatch.handle.branchName}).`),failedSettlement}let preCleanupRenewFailure=renewRecoveryClaimLease("before cleanup/finalization",mergeResult.provenance);if(preCleanupRenewFailure)return preCleanupRenewFailure;let cleanupResult=await cleanupStandardWorktreeForCallId(resolvedCallID,"success",directory,dispatch.worktree_dir,{retainBranch:mergeResult.strategy==="squash-unstaged"});if(dispatch.recoveryClaim){let request={authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken,settlement:dispatch.recoveryClaim.settlement};if(cleanupResult.removedWorktree&&cleanupResult.cleanedBranch){let finalized=_internals79.finalizeWorktreeRecoveryAuthority(directory,request);if(!finalized.ok)return failRecoverySettlement("recovery-claim-finalize",`The merged recovery lane was cleaned up but could not finalize its exact claim; ${describeRecoveryMutationFailure({action:"finalize",code:finalized.code,reason:finalized.reason})}`,mergeResult.provenance)}else{let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure}}clearWorktreeMergeStatus(statusKey);try{let{removeLaneProfileFromDiskReal:removeLaneProfileFromDiskReal2}=await Promise.resolve().then(() => (init_core3(),exports_core3));await removeLaneProfileFromDiskReal2(dispatch.handle.worktreePath,dispatch.laneIndex)}catch{}let state2=serializationStateBySessionID.get(dispatch.parentSessionID);if(state2)state2.successfulDispatchesSince++,checkStandardWorktreeSerializationRelease(dispatch.parentSessionID,wtConfig);try{verifyReviewerScopeGenerationMergeBack({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID,primaryDirectory:directory})}catch{}return mergedSettlement}if("partial"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance,mergeResult.conflictFiles);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);pushAdvisory(session,`STANDARD_WORKTREE_MERGE_PARTIAL: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; stage: ${mergeResult.stage}; ${mergeResult.message}`+(mergeResult.code?` (code: ${mergeResult.code})`:"")+(mergeResult.recoveryHint?` ${mergeResult.recoveryHint}`:""));try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"partial",stage:mergeResult.stage,message:mergeResult.message,autoCommitted:mergeResult.autoCommitted,cleaned:mergeResult.cleaned,conflictFiles:mergeResult.conflictFiles,code:mergeResult.code,recoveryHint:mergeResult.recoveryHint,provenance:mergeResult.provenance}}if("failed"in mergeResult){let publishFailure=await publishRecoveryAuthority(mergeResult.provenance);if(publishFailure)return publishFailure;let releaseFailure=releaseRecoveryClaim(mergeResult.provenance);if(releaseFailure)return releaseFailure;recordWorktreeMergeFailure(statusKey,{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID),location=mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE||mergeResult.stage===SOURCE_WORKTREE_UNCERTAIN_STAGE?`lane worktree ${dispatch.handle.worktreePath} no longer exists`:`preserved at ${dispatch.handle.worktreePath}`;pushAdvisory(session,`STANDARD_WORKTREE_MERGE_FAILED: task ${dispatch.taskId} ${location}; stage: ${mergeResult.stage}; ${mergeResult.message}.`);try{markReviewerScopeGenerationMergebackPending({parentSessionID:dispatch.parentSessionID,taskId:statusKey,coderCallID:resolvedCallID})}catch{}return{outcome:"failed",stage:mergeResult.stage,message:mergeResult.message,provenance:mergeResult.provenance}}return{outcome:"failed",stage:"merge",message:"Merge-back returned an unexpected result"}},queuedRun=standardWorktreeMergeQueue.then(run,run);standardWorktreeMergeQueue=queuedRun;let result;try{result=await queuedRun}catch(error49){if(standardWorktreeByCallID.delete(resolvedCallID),awaitingMergeByCallID.delete(resolvedCallID),dispatch.recoveryClaim)try{_internals79.releaseWorktreeRecoveryClaim(directory,{authorityDigest:dispatch.recoveryClaim.authorityDigest,claimantCallID:resolvedCallID,claimRevision:dispatch.recoveryClaim.claimRevision,rawToken:dispatch.recoveryClaim.rawToken})}catch{}let message=`Unexpected worktree settlement failure: ${error49 instanceof Error?error49.message:String(error49)}`;recordWorktreeMergeFailure(dispatch.planTaskId??dispatch.taskId,{outcome:"failed",stage:"merge",message,worktreePath:dispatch.handle.worktreePath,branch:dispatch.handle.branchName,completedAt:Date.now()});let session=ensureAgentSession(dispatch.parentSessionID);return pushAdvisory(session,`STANDARD_WORKTREE_SETTLEMENT_FAILED: task ${dispatch.taskId} preserved at ${dispatch.handle.worktreePath}; ${message}.`),{outcome:"failed",stage:"merge",message}}if(resolvedCallID)awaitingMergeByCallID.delete(resolvedCallID);return result}async function readLaneEnvFileFromDisk(worktreePath,laneIndex){let envPath=path95.join(worktreePath,".swarm","lanes",`${laneIndex}.env`),content;try{content=await fs61.readFile(envPath,"utf-8")}catch(err){if(err.code==="ENOENT")return{};return log(`[worktree-isolation] failed to read lane env file ${envPath}: ${err.message}`),{}}let result={};for(let rawLine of content.split(`
1264
- `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_RECOVERY_CLAIM_LEASE_MS=300000,WORKTREE_SESSION_CREATE_TIMEOUT_MS=30000,WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS=5000,StandardWorktreeLifecycleError,standardWorktreeDegradationReasonBySession,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals79;var init_worktree_isolation=__esm(()=>{init_constants();init_project_db();init_file_locks();init_lane_owners();init_executor();init_state2();init_bun_compat();init_canonical_root();init_ephemeral_session_teardown();init_git_executable();init_logger();init_timeout();init_worktree();init_merge2();init_reviewer_scope_mergeback();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;StandardWorktreeLifecycleError=class StandardWorktreeLifecycleError extends Error{kind="standard-worktree-lifecycle";constructor(message){super(message);this.name="StandardWorktreeLifecycleError"}};standardWorktreeDegradationReasonBySession=new Map;_internals79={provisionWorktree,removeWorktree,attemptMergeBackFromDirty,recoverMergeBackFromImmutableCoordinates,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,lookupWorktreeRecoveryAuthoritiesByTask,claimWorktreeRecoveryAuthority,renewWorktreeRecoveryClaim,releaseWorktreeRecoveryClaim,finalizeWorktreeRecoveryAuthority,publishWorktreeRecoveryAuthority,replayWorktreeRecoveryClaimJournal,buildWorktreeRecoveryPublishIdentity,preserveDirtyWorktreeAtPath,worktreeSessionCreateTimeoutMs:WORKTREE_SESSION_CREATE_TIMEOUT_MS,worktreeSessionCreateSettleGraceMs:WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS,createSessionWithinBudget,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});var exports_coder_settlement={};__export(exports_coder_settlement,{transferCoderSettlementToBackground:()=>transferCoderSettlementToBackground,settleCoderDispatch:()=>settleCoderDispatch,releaseCoderDispatchOwnership:()=>releaseCoderDispatchOwnership,recoverStaleCoderSettlements:()=>recoverStaleCoderSettlements,recoverCoderSettlement:()=>recoverCoderSettlement,recordCoderMergeProvenance:()=>recordCoderMergeProvenance,listCoderSettlementWalStates:()=>listCoderSettlementWalStates,completeCoderSettlementCleanup:()=>completeCoderSettlementCleanup,beginCoderSettlement:()=>beginCoderSettlement,assertNoUnsettledCoderDispatch:()=>assertNoUnsettledCoderDispatch,abortCoderSettlementIfDoomed:()=>abortCoderSettlementIfDoomed,abortCoderSettlement:()=>abortCoderSettlement,_internals:()=>_internals86});import{spawnSync as spawnSync9}from"node:child_process";import{randomUUID as randomUUID14}from"node:crypto";import{existsSync as existsSync48}from"node:fs";import{readdir as readdir6}from"node:fs/promises";function dispatchKey(directory,taskId,transitionId){return`${canonicalRootKeyFresh(directory)}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal2(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal3(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){try{appendCoreEventSync(directory,{type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}catch(error49){criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive3(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error49){return error49.code==="EPERM"}}async function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=await changedFilesSinceSnapshotAsync(directory,baseline);if(!observed||!context.declaredFiles)return null;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}function settlementTransitionEvent(wal){return wal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:wal.testEngineerExempt===!0,settlementFailed:wal.settlementFailed===!0},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}}function withLandedUnstaged(worktree,landedUnstaged){if(worktree===void 0||landedUnstaged===void 0)return worktree;return{...worktree,landedUnstaged}}async function commitPrepared(directory,wal,options){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal2(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let transitionEvent=settlementTransitionEvent(lockedWal),snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.generation===lockedWal.expectedGeneration&&snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId){let evidence2=transaction.read();if(lockedWal.accepted===!0)await ensureTaskGateRequirementsReceiptForSettledTransition(directory,lockedWal.taskId,evidence2,transitionEvent);if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED")throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence=await transaction.transition(transitionEvent);return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){if(options.context.baseline.gitHead===null){if((await captureWorkspaceSnapshotAsync(options.directory)).gitHead!==null)throw Error(`CODER_SETTLEMENT_BASELINE_UNAVAILABLE: the launch baseline for task ${options.taskId} has no git HEAD — the observation directory (${options.context.baseline.directory}) is not a git repository or git is unavailable there. An unregistered worktree lane (a lane directory that git worktree list does not know) produces exactly this. The task was not dispatched and no settlement state was created; retry the dispatch, or set worktree.policy "disabled" to run coders in the primary tree.`)}let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal2(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal3(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key2=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key2)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key2)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="COMMITTED"){if(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal,{landedUnstaged:options.landedUnstaged})}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted:options.accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed:options.settlementFailed===!0};if(wal.state!=="PREPARED")await writeWal3(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared,{landedUnstaged:options.landedUnstaged})}finally{let finalWal=await readWal2(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error49){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}return outcome}async function transferCoderSettlementToBackground(options){return withSettlementLock(options.directory,options.taskId,"coder-background-transfer",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)return"missing";if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="PREPARED")throw Error("CODER_SETTLEMENT_IN_PROGRESS");if(wal.state!=="DISPATCHED")return liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),"already-terminal";let reason="ownership transferred to durable background completion";return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason,cleanupComplete:!0}),liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),await appendSettlementEvent(options.directory,"aborted",wal,{reason,ownership:"background-delegation"}),"transferred"})}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal2(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal3(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync9(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor,options){let retainBranch=options?.retainBranch??descriptor.landedUnstaged===!0,branchExists=()=>_internals86.branchExists(directory,descriptor.branchName),hasResidue=existsSync48(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0,retainBranch?{retainBranch:!0}:void 0);if(existsSync48(descriptor.worktreePath)||branchExists()&&!retainBranch)throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let provisioningOwner=descriptor.provisioningOwner??(descriptor.reservationId!==void 0&&descriptor.generation!==void 0?{reservationId:descriptor.reservationId,generation:descriptor.generation,branchName:descriptor.branchName}:void 0);if(!_internals86.removeWorktreeProvisioningOwner(directory,descriptor.callID,provisioningOwner))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync48(descriptor.worktreePath))return!1;if(_internals86.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal2(filePath,taskId);if(healedWal!==null)await writeWal3(filePath,{...healedWal,cleanupComplete:!0})}catch(error49){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error49 instanceof Error?error49.message:String(error49)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal2(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0});return null}let key2=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key2)||wal.processId!==process.pid&&isProcessAlive3(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??await scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for isolated task ${taskId} could not attribute worktree changes to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){let landedUnstaged=landed.method==="worktree-match";wal={...wal,state:"PREPARED",observedFiles:observed2,accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal);let committed2=await commitPrepared(directory,wal,{landedUnstaged});await cleanupRecoveredWorktree(directory,worktree,{retainBranch:landedUnstaged});let reconciledWal=await readWal2(filePath,taskId);if(reconciledWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...reconciledWal,cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} could not reconcile the landed merge (${filePath}, state ${wal.state}): ${landed.error}. Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal3(filePath,wal)},onMerged:async(mergedResult)=>{wal={...wal,state:"PREPARED",accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal),recovered=await commitPrepared(directory,wal,{landedUnstaged:mergedResult.strategy==="squash-unstaged"})}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: transition ${wal.transitionId} for task ${taskId} worktree merge-back did not reach merged (${filePath}, state ${wal.state}, outcome ${mergeResult.outcome}${mergeResult.outcome==="failed"&&mergeResult.message?`: ${mergeResult.message}`:""}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}await cleanupRecoveredWorktree(directory,descriptor,{retainBranch:mergeResult.strategy==="squash-unstaged"});let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=await changedFilesSinceSnapshotAsync(directory,wal.context.baseline),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted2=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted2.outcome==="aborted"||aborted2.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} workspace changes could not be attributed to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);wal={...wal,state:"PREPARED",accepted:observed.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal3(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal3(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir6(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal2(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,accepted:wal.accepted===!0?!0:void 0,declaredFiles:wal.context?.declaredFiles??null,expectedGeneration:wal.expectedGeneration,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive3(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals86.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error49){results.push({taskId:entry.taskId,outcome:"error",message:error49 instanceof Error?error49.message:String(error49)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals86.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal2(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted,previousTransitionId:entry.transitionId??"",previousState:entry.state,...typeof entry.expectedGeneration==="number"?{expectedGeneration:entry.expectedGeneration}:{}}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error49){let message=error49 instanceof Error?error49.message:String(error49);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry2,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals86;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_core_events();init_gate_evidence();init_gate_evidence_classification();init_worktree_provisioning_owner();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_canonical_root();init_git_executable();init_logger();init_merge2();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry2=globalThis;if(!globalRegistry2[LIVE_DISPATCHES_SYMBOL])globalRegistry2[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry2[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID14();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals86={liveDispatches,removeWorktreeProvisioningOwner,branchExists:probeBranchExists,recoverCoderSettlement}});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,replacePendingBackgroundAdvisory:()=>replacePendingBackgroundAdvisory,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,registerStaleSweepObserver:()=>registerStaleSweepObserver,registerLegacyCoderSettlementReconciler:()=>registerLegacyCoderSettlementReconciler,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegationsDetailed:()=>readDelegationsDetailed,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,publishPrReviewResultReceipt:()=>publishPrReviewResultReceipt,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,markLegacyCoderSettlementTransferPending:()=>markLegacyCoderSettlementTransferPending,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,isTerminalDelegationStatus:()=>isTerminalDelegationStatus,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationIdDetailed:()=>findByCorrelationIdDetailed,findByCorrelationId:()=>findByCorrelationId,findByBatchIdDetailed:()=>findByBatchIdDetailed,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,clearLegacyCoderSettlementTransferPending:()=>clearLegacyCoderSettlementTransferPending,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_internals:()=>_internals87,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER:()=>LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER,DELEGATION_READ_RETRY_DELAY_MS:()=>DELEGATION_READ_RETRY_DELAY_MS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash45}from"node:crypto";import*as fs62 from"node:fs";import*as path96 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath5(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath2(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function importedShadowPath2(filePath){return`${filePath}.imported`}function projectionMarkerPath2(filePath){return`${filePath}.sqlite-projection`}function coordinationReservationLeaseKey(reservation){return{namespace:RESERVATION_LEASE_NAMESPACE,entityKey:reservation.reservationId,generation:reservation.generation??1,ownerToken:reservation.reservationId}}function releaseReservationLeaseIfPresent(directory,reservation){let leaseKey=coordinationReservationLeaseKey(reservation),existing=getCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey);if(!existing)return;if(existing.generation!==leaseKey.generation||existing.ownerToken!==leaseKey.ownerToken||!releaseCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey,leaseKey.generation,leaseKey.ownerToken))throw Error(`reservation lease authority mismatch for ${reservation.reservationId}`)}function coordinationRowsToDelegations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=RecordSchema2.safeParse(JSON.parse(row.payload));if(!parsed.success||parsed.data.correlationId!==row.entityKey||Math.max(parsed.data.generation??1,1)!==row.generation||parsed.data.status!==row.status)throw Error(`delegation coordination row failed schema or authority binding validation for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.correlationId.localeCompare(right.correlationId):left.createdAt-right.createdAt)}catch(error49){return recordLedgerUncertainty(directory,error49 instanceof Error?error49.message:String(error49),"coordination-read"),null}}function archiveShadowFileBestEffort2(filePath){if(!fs62.existsSync(filePath))return;let importedPath=importedShadowPath2(filePath);try{if(fs62.existsSync(importedPath))return;fs62.renameSync(filePath,importedPath)}catch(error49){warn(`[background] shadow archive failed for ${path96.basename(filePath)}: ${error49 instanceof Error?error49.message:String(error49)}`)}}function writeDelegationShadowProjection(directory,records){ensureSwarmDir4(directory);let payload=records.map((record2)=>JSON.stringify(record2)).join(`
1264
+ `)){let line=rawLine.trim();if(!line||line.startsWith("#"))continue;let eqIdx=line.indexOf("=");if(eqIdx<0)continue;let k=line.slice(0,eqIdx),v=line.slice(eqIdx+1);if(!isValidEnvKey(k))continue;if(isUntrustedEnvKey(k))continue;result[k]=v}return result}var MAX_TRACKED_STANDARD_WORKTREE_CALLS=256,awaitingMergeByCallID,standardWorktreeByCallID,standardWorktreeSerializationSessions,standardWorktreeMergeQueue,standardWorktreeLaneIndexBySession,serializationStateBySessionID,WORKTREE_RECOVERY_CLAIM_LEASE_MS=300000,WORKTREE_SESSION_CREATE_TIMEOUT_MS=30000,WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS=5000,StandardWorktreeLifecycleError,standardWorktreeDegradationReasonBySession,WORKTREE_LIST_TIMEOUT_MS=15000,PRESERVE_COMMIT_TIMEOUT_MS=30000,_internals79;var init_worktree_isolation=__esm(()=>{init_constants();init_project_db();init_file_locks();init_lane_owners();init_executor();init_state2();init_bun_compat();init_canonical_root();init_ephemeral_session_teardown();init_git_executable();init_logger();init_timeout();init_worktree();init_merge2();init_reviewer_scope_mergeback();init_dead_lane_reclaim();init_worktree_merge_status();init_worktree_provisioning_owner();init_worktree_recovery_authority();init_worktree_isolation_config();awaitingMergeByCallID=new Map,standardWorktreeByCallID=new Map,standardWorktreeSerializationSessions=new Set,standardWorktreeMergeQueue=Promise.resolve(),standardWorktreeLaneIndexBySession=new Map,serializationStateBySessionID=new Map;StandardWorktreeLifecycleError=class StandardWorktreeLifecycleError extends Error{kind="standard-worktree-lifecycle";constructor(message){super(message);this.name="StandardWorktreeLifecycleError"}};standardWorktreeDegradationReasonBySession=new Map;_internals79={provisionWorktree,removeWorktree,attemptMergeBackFromDirty,recoverMergeBackFromImmutableCoordinates,postMergeCleanup,pruneStaleWorktreeMetadata,readLaneEnvFileFromDisk,serializationStateBySessionID,rememberStandardWorktreeSerializationSession,awaitingMergeByCallID,startupOrphanRecovery,cleanupOrphanedBranches,cleanupStandardWorktreeForCallId,preserveDirtyWorktreeForCallId,preserveBackgroundWorktreeOwnershipForCallId,tryAcquireWorktreeLifecycleLock:tryAcquireLock,recordWorktreeProvisioningOwner,removeWorktreeProvisioningOwner,lookupWorktreeRecoveryAuthoritiesByTask,claimWorktreeRecoveryAuthority,renewWorktreeRecoveryClaim,releaseWorktreeRecoveryClaim,finalizeWorktreeRecoveryAuthority,publishWorktreeRecoveryAuthority,replayWorktreeRecoveryClaimJournal,buildWorktreeRecoveryPublishIdentity,preserveDirtyWorktreeAtPath,worktreeSessionCreateTimeoutMs:WORKTREE_SESSION_CREATE_TIMEOUT_MS,worktreeSessionCreateSettleGraceMs:WORKTREE_SESSION_CREATE_SETTLE_GRACE_MS,createSessionWithinBudget,abortStandardWorktreeDispatch,standardWorktreeByCallID,preProvisionCollisionCheck,inspectStandardWorktreeCollisionOwnership:inspectStandardWorktreeCollisionOwnership2,isLaneOwnedByCurrentSession,bunSpawn,resolveGitExecutable}});var exports_coder_settlement={};__export(exports_coder_settlement,{transferCoderSettlementToBackground:()=>transferCoderSettlementToBackground,settleCoderDispatch:()=>settleCoderDispatch,releaseCoderDispatchOwnership:()=>releaseCoderDispatchOwnership,recoverStaleCoderSettlements:()=>recoverStaleCoderSettlements,recoverCoderSettlement:()=>recoverCoderSettlement,recordCoderMergeProvenance:()=>recordCoderMergeProvenance,listCoderSettlementWalStates:()=>listCoderSettlementWalStates,completeCoderSettlementCleanup:()=>completeCoderSettlementCleanup,beginCoderSettlement:()=>beginCoderSettlement,assertNoUnsettledCoderDispatch:()=>assertNoUnsettledCoderDispatch,abortCoderSettlementIfDoomed:()=>abortCoderSettlementIfDoomed,abortCoderSettlement:()=>abortCoderSettlement,_internals:()=>_internals86});import{spawnSync as spawnSync9}from"node:child_process";import{randomUUID as randomUUID14}from"node:crypto";import{existsSync as existsSync48}from"node:fs";import{readdir as readdir6}from"node:fs/promises";function dispatchKey(directory,taskId,transitionId){return`${canonicalRootKeyFresh(directory)}\x00${taskId}\x00${transitionId}`}function walPath(directory,taskId){return validateSwarmPath(directory,`coder-settlements/${taskId}.json`)}async function readWal2(filePath,taskId){return readWorkflowWalFile("coder-settlement",filePath,taskId)}async function withSettlementLock(directory,taskId,actor,operation){let target=`coder-settlements/${taskId}.json`,lock=await tryAcquireLock(directory,target,actor,`coder-settlement-${taskId}-${Date.now()}`);if(!lock.acquired)throw Error(`CODER_SETTLEMENT_LOCKED: task ${taskId}`);try{return await operation()}finally{await lock.lock._release?.().catch(()=>{return})}}async function writeWal3(filePath,wal){await writeWorkflowWalFile("coder-settlement",filePath,wal)}async function appendSettlementEvent(directory,action,wal,extra){try{appendCoreEventSync(directory,{type:"coder_settlement",action,timestamp:new Date().toISOString(),taskId:wal.taskId,transitionId:wal.transitionId,actor:wal.actor,...extra??{}})}catch(error49){criticalWarn(`[coder-settlement] lifecycle event write failed (${action} ${wal.taskId}): ${error49 instanceof Error?error49.message:String(error49)}`)}}function baselineAttributionDoomed(baseline){if(baseline.gitHead===null)return!0;return Array.isArray(baseline.changedFiles)&&baseline.changedFiles.length>0}function doomedReason(baseline){if(baseline.gitHead===null)return"launch workspace has no git baseline (not a git repository, or git unavailable at dispatch)";return`launch baseline was dirty with ${String(baseline.changedFiles?.length??0)} pre-existing uncommitted/untracked change(s)`}function isProcessAlive3(processId){if(processId===process.pid)return!0;try{return process.kill(processId,0),!0}catch(error49){return error49.code==="EPERM"}}async function scopedObservedFiles(directory,context){let baseline={...context.baseline,directory},observed=await changedFilesSinceSnapshotAsync(directory,baseline);if(!observed||!context.declaredFiles)return null;return observed.filter((filePath)=>isPathWithinDeclaredScope(filePath,context.declaredFiles??[],directory))}function settlementTransitionEvent(wal){return wal.accepted?{type:"accepted_mutation",agentType:"coder",context:{testEngineerExempt:wal.testEngineerExempt===!0,settlementFailed:wal.settlementFailed===!0},expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}:{type:"dispatch_no_mutation",agentType:"coder",expectedGeneration:wal.expectedGeneration,transitionId:wal.transitionId}}function withLandedUnstaged(worktree,landedUnstaged){if(worktree===void 0||landedUnstaged===void 0)return worktree;return{...worktree,landedUnstaged}}async function commitPrepared(directory,wal,options){return withTaskEvidenceTransaction(directory,wal.taskId,wal.actor,async(transaction)=>{let lockedWal=await readWal2(walPath(directory,wal.taskId),wal.taskId);if(lockedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(lockedWal.transitionId!==wal.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");let transitionEvent=settlementTransitionEvent(lockedWal),snapshot=getTaskWorkflowSnapshot(transaction.read());if(lockedWal.accepted===!0?snapshot.authoritative&&snapshot.state===(lockedWal.settlementFailed===!0?"rework_required":"coder_delegated")&&snapshot.generation===lockedWal.expectedGeneration+1&&snapshot.lastOutcome===(lockedWal.settlementFailed===!0?"accepted_mutation_failed":"accepted_mutation")&&snapshot.lastTransitionId===lockedWal.transitionId:snapshot.generation===lockedWal.expectedGeneration&&snapshot.lastOutcome==="dispatch_no_mutation"&&snapshot.lastTransitionId===lockedWal.transitionId){let evidence2=transaction.read();if(lockedWal.accepted===!0)await ensureTaskGateRequirementsReceiptForSettledTransition(directory,lockedWal.taskId,evidence2,transitionEvent);if(lockedWal.state!=="COMMITTED")lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal,{resumed:!0});return{evidence:evidence2,accepted:lockedWal.accepted===!0,alreadyApplied:!0}}if(lockedWal.state!=="PREPARED")throw Error("CODER_SETTLEMENT_NOT_PREPARED");let evidence=await transaction.transition(transitionEvent);return lockedWal={...lockedWal,state:"COMMITTED",cleanupComplete:lockedWal.worktree===void 0,worktree:withLandedUnstaged(lockedWal.worktree,options?.landedUnstaged)},await writeWal3(walPath(directory,wal.taskId),lockedWal),await appendSettlementEvent(directory,"settled",lockedWal),{evidence,accepted:lockedWal.accepted===!0,alreadyApplied:!1}})}async function beginCoderSettlement(options){if(options.context.baseline.gitHead===null){if((await captureWorkspaceSnapshotAsync(options.directory)).gitHead!==null)throw Error(`CODER_SETTLEMENT_BASELINE_UNAVAILABLE: the launch baseline for task ${options.taskId} has no git HEAD — the observation directory (${options.context.baseline.directory}) is not a git repository or git is unavailable there. An unregistered worktree lane (a lane directory that git worktree list does not know) produces exactly this. The task was not dispatched and no settlement state was created; retry the dispatch, or set worktree.policy "disabled" to run coders in the primary tree.`)}let filePath=walPath(options.directory,options.taskId),ownsActiveDispatch=!1;if(await withSettlementLock(options.directory,options.taskId,options.actor,()=>withTaskEvidenceTransaction(options.directory,options.taskId,options.actor,async(transaction)=>{let snapshot=getTaskWorkflowSnapshot(transaction.read());if(snapshot.generation!==options.expectedGeneration)throw Error(`TASK_WORKFLOW_GENERATION_MISMATCH: expected ${options.expectedGeneration}, found ${snapshot.generation}`);let existing=await readWal2(filePath,options.taskId);if(existing!==null){if((existing.state==="DISPATCHED"||existing.state==="PREPARED")&&existing.transitionId!==options.transitionId)throw Error(`CODER_SETTLEMENT_IN_PROGRESS: transition ${existing.transitionId} owns task ${options.taskId}, so transition ${options.transitionId} cannot dispatch it (${filePath}, state ${existing.state}). Wait for the owning transition to settle or run /swarm recover ${options.taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(existing.transitionId===options.transitionId){if(!(existing.actor===options.actor&&existing.expectedGeneration===options.expectedGeneration&&JSON.stringify(existing.context)===JSON.stringify(options.context)&&JSON.stringify(existing.worktree)===JSON.stringify(options.worktree)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(existing.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");ownsActiveDispatch=existing.state==="DISPATCHED"&&existing.runtimeId===runtimeId;return}}await transaction.transition({type:"dispatch_attempted",agentType:"coder",expectedGeneration:options.expectedGeneration,transitionId:options.transitionId}),await writeWal3(filePath,{version:1,state:"DISPATCHED",taskId:options.taskId,transitionId:options.transitionId,actor:options.actor,processId:process.pid,runtimeId,expectedGeneration:options.expectedGeneration,context:options.context,...options.worktree?{worktree:options.worktree}:{},recordedAt:new Date().toISOString()}),ownsActiveDispatch=!0,await appendSettlementEvent(options.directory,"dispatched",{taskId:options.taskId,transitionId:options.transitionId,actor:options.actor})})),ownsActiveDispatch){let key2=dispatchKey(options.directory,options.taskId,options.transitionId);if(!liveDispatches.has(key2)&&liveDispatches.size>=MAX_LIVE_DISPATCHES)throw Error("CODER_SETTLEMENT_CAPACITY_EXCEEDED");liveDispatches.add(key2)}}async function settleCoderDispatch(options){return withSettlementLock(options.directory,options.taskId,"coder-settlement",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="COMMITTED"){if(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return commitPrepared(options.directory,wal,{landedUnstaged:options.landedUnstaged})}if(wal.state==="ABORTED")throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");if(wal.state==="PREPARED"&&(wal.accepted!==options.accepted||wal.testEngineerExempt!==options.testEngineerExempt||wal.settlementFailed!==(options.settlementFailed===!0)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");let prepared={...wal,state:"PREPARED",accepted:options.accepted,testEngineerExempt:options.testEngineerExempt,settlementFailed:options.settlementFailed===!0};if(wal.state!=="PREPARED")await writeWal3(filePath,prepared);liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId));try{return await commitPrepared(options.directory,prepared,{landedUnstaged:options.landedUnstaged})}finally{let finalWal=await readWal2(filePath,options.taskId);if(finalWal!==null&&finalWal.state==="COMMITTED")liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId))}})}async function abortCoderSettlement(options){let{outcome,worktree}=await withSettlementLock(options.directory,options.taskId,"coder-abort",async()=>abortDispatchedWalUnderLock(options.directory,options.taskId,options.transitionId,options.reason));if(worktree&&outcome!=="not-dispatched")try{await completeCoderSettlementCleanup(options.directory,options.taskId,options.transitionId)}catch(error49){criticalWarn(`[coder-settlement] aborted settlement worktree cleanup failed for task ${options.taskId}: ${error49 instanceof Error?error49.message:String(error49)}`)}return outcome}async function transferCoderSettlementToBackground(options){return withSettlementLock(options.directory,options.taskId,"coder-background-transfer",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)return"missing";if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="PREPARED")throw Error("CODER_SETTLEMENT_IN_PROGRESS");if(wal.state!=="DISPATCHED")return liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),"already-terminal";let reason="ownership transferred to durable background completion";return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason,cleanupComplete:!0}),liveDispatches.delete(dispatchKey(options.directory,options.taskId,options.transitionId)),await appendSettlementEvent(options.directory,"aborted",wal,{reason,ownership:"background-delegation"}),"transferred"})}async function abortDispatchedWalUnderLock(directory,taskId,transitionId,reason){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state==="ABORTED")return{outcome:"already-aborted",worktree:wal.worktree!==void 0};if(wal.state!=="DISPATCHED")return{outcome:"not-dispatched",worktree:!1};return await writeWal3(filePath,{...wal,state:"ABORTED",abortReason:reason}),liveDispatches.delete(dispatchKey(directory,taskId,transitionId)),await appendSettlementEvent(directory,"aborted",wal,{reason}),{outcome:"aborted",worktree:wal.worktree!==void 0}}async function abortCoderSettlementIfDoomed(options){let filePath=walPath(options.directory,options.taskId),wal;try{wal=await readWal2(filePath,options.taskId)}catch{return"not-doomed"}if(wal===null)return"not-doomed";if(wal.state==="ABORTED")return"already-aborted";if(wal.transitionId!==options.transitionId||wal.state!=="DISPATCHED")return"not-doomed";if(!baselineAttributionDoomed(wal.context.baseline))return"not-doomed";let outcome=await abortCoderSettlement({directory:options.directory,taskId:options.taskId,transitionId:options.transitionId,reason:doomedReason(wal.context.baseline)});return outcome==="aborted"||outcome==="already-aborted"?outcome:"not-doomed"}async function recordCoderMergeProvenance(options){await withSettlementLock(options.directory,options.taskId,"coder-merge-provenance",async()=>{let filePath=walPath(options.directory,options.taskId),wal=await readWal2(filePath,options.taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==options.taskId||wal.transitionId!==options.transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="DISPATCHED"){if(!(JSON.stringify(wal.mergeProvenance)===JSON.stringify(options.provenance)&&JSON.stringify(wal.observedFiles)===JSON.stringify(options.observedFiles)))throw Error("CODER_SETTLEMENT_IDEMPOTENCY_CONFLICT");return}await writeWal3(filePath,{...wal,mergeProvenance:options.provenance,observedFiles:[...options.observedFiles]})})}function probeBranchExists(directory,branchName){let result=spawnSync9(resolveGitExecutable(),["-C",directory,"show-ref","--verify","--quiet",`refs/heads/${branchName}`],{cwd:directory,stdio:["ignore","ignore","ignore"],timeout:5000,windowsHide:!0});if(result.error)throw result.error;if(result.status===0)return!0;if(result.status===1)return!1;throw Error(`CODER_SETTLEMENT_CLEANUP_UNCERTAIN: git show-ref exited with status ${String(result.status)}`)}async function cleanupRecoveredWorktree(directory,descriptor,options){let retainBranch=options?.retainBranch??descriptor.landedUnstaged===!0,branchExists=()=>_internals86.branchExists(directory,descriptor.branchName),hasResidue=existsSync48(descriptor.worktreePath)||branchExists(),{awaitingMergeByCallID:awaitingMergeByCallID2,cleanupStandardWorktreeForCallId:cleanupStandardWorktreeForCallId2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation));if(standardWorktreeByCallID2.delete(descriptor.callID),hasResidue)awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});if(hasResidue)await cleanupStandardWorktreeForCallId2(descriptor.callID,"success",directory,descriptor.worktreeDir??void 0,retainBranch?{retainBranch:!0}:void 0);if(existsSync48(descriptor.worktreePath)||branchExists()&&!retainBranch)throw Error("CODER_SETTLEMENT_WORKTREE_CLEANUP_UNVERIFIED");let provisioningOwner=descriptor.provisioningOwner??(descriptor.reservationId!==void 0&&descriptor.generation!==void 0?{reservationId:descriptor.reservationId,generation:descriptor.generation,branchName:descriptor.branchName}:void 0);if(!_internals86.removeWorktreeProvisioningOwner(directory,descriptor.callID,provisioningOwner))throw Error("CODER_SETTLEMENT_OWNER_CLEANUP_FAILED")}async function completeCoderSettlementCleanup(directory,taskId,transitionId){await withSettlementLock(directory,taskId,"coder-cleanup",async()=>{let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");if(wal.taskId!==taskId||wal.transitionId!==transitionId)throw Error("CODER_SETTLEMENT_WAL_REPLACED");if(wal.state!=="COMMITTED"&&wal.state!=="ABORTED")throw Error("CODER_SETTLEMENT_NOT_COMMITTED");if(!wal.worktree||wal.cleanupComplete===!0)return;await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0})})}async function selfHealMissingLaneWorktree(directory,filePath,taskId,transitionId,descriptor,detail){if(existsSync48(descriptor.worktreePath))return!1;if(_internals86.branchExists(directory,descriptor.branchName))return!1;let reason=`CODER_SETTLEMENT_SELF_HEALED_MISSING_WORKTREE: ${detail}`;if((await abortDispatchedWalUnderLock(directory,taskId,transitionId,reason)).outcome==="not-dispatched")return!1;try{await cleanupRecoveredWorktree(directory,descriptor);let healedWal=await readWal2(filePath,taskId);if(healedWal!==null)await writeWal3(filePath,{...healedWal,cleanupComplete:!0})}catch(error49){criticalWarn(`[coder-settlement] self-healed task ${taskId} but residual cleanup failed: ${error49 instanceof Error?error49.message:String(error49)}`)}let message=`STALE_CODER_SETTLEMENT_SELF_HEALED: task ${taskId} was blocked by a coder settlement whose lane worktree "${descriptor.worktreePath}" and lane branch "${descriptor.branchName}" no longer exist. Nothing was recoverable, so the write-ahead log at "${filePath}" was marked terminal (ABORTED) and the task was unblocked. Re-dispatch the task if its work still needs doing.`;return criticalWarn(message),advisoryWarn(message),!0}async function recoverCoderSettlement(directory,taskId){return withSettlementLock(directory,taskId,"coder-recovery",async()=>{let filePath=walPath(directory,taskId),existingWal=await readWal2(filePath,taskId);if(existingWal===null)return null;let wal=existingWal;if(wal.state==="ABORTED")return null;if(wal.state==="COMMITTED"){if(wal.worktree&&wal.cleanupComplete!==!0)await cleanupRecoveredWorktree(directory,wal.worktree),await writeWal3(filePath,{...wal,cleanupComplete:!0});return null}let key2=dispatchKey(directory,taskId,wal.transitionId);if(liveDispatches.has(key2)||wal.processId!==process.pid&&isProcessAlive3(wal.processId))throw Error(`CODER_DISPATCH_IN_PROGRESS: transition ${wal.transitionId} still owns task ${taskId} (${filePath}, state ${wal.state}, pid ${wal.processId}). Wait for that dispatch to settle or run /swarm recover ${taskId} (or /swarm reset-session) to unwedge it; do not remove the WAL by hand.`);if(wal.state==="DISPATCHED"){if(wal.worktree){let worktree=wal.worktree,observed2=wal.observedFiles??await scopedObservedFiles(worktree.worktreePath,wal.context);if(observed2===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for isolated task ${taskId} could not attribute worktree changes to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);if(wal.mergeProvenance){let landed=await reconcileLandedMerge(directory,wal.mergeProvenance);if(landed.landed){let landedUnstaged=landed.method==="worktree-match";wal={...wal,state:"PREPARED",observedFiles:observed2,accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal);let committed2=await commitPrepared(directory,wal,{landedUnstaged});await cleanupRecoveredWorktree(directory,worktree,{retainBranch:landedUnstaged});let reconciledWal=await readWal2(filePath,taskId);if(reconciledWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...reconciledWal,cleanupComplete:!0}),committed2}if(landed.error)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} could not reconcile the landed merge (${filePath}, state ${wal.state}): ${landed.error}. Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}let{awaitingMergeByCallID:awaitingMergeByCallID2,finishStandardWorktreeDispatch:finishStandardWorktreeDispatch2,standardWorktreeByCallID:standardWorktreeByCallID2}=await Promise.resolve().then(() => (init_worktree_isolation(),exports_worktree_isolation)),descriptor=wal.worktree,reconstructedDispatch={callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},handle:{worktreePath:descriptor.worktreePath,branchName:descriptor.branchName,purpose:"lane",id:descriptor.worktreeId,sessionId:descriptor.worktreeSessionId},mergeStrategy:descriptor.mergeStrategy,laneIndex:descriptor.laneIndex,...descriptor.worktreeDir?{worktree_dir:descriptor.worktreeDir}:{}};standardWorktreeByCallID2.delete(descriptor.callID),awaitingMergeByCallID2.set(descriptor.callID,{callID:descriptor.callID,parentSessionID:descriptor.parentSessionId,taskId:descriptor.taskId,...descriptor.planTaskId?{planTaskId:descriptor.planTaskId}:{},branch:descriptor.branchName,worktreePath:descriptor.worktreePath,mergeStrategy:descriptor.mergeStrategy,queuedAt:Date.now()});let recovered=null,mergeResult=await finishStandardWorktreeDispatch2(directory,reconstructedDispatch,void 0,descriptor.callID,{operationId:wal.transitionId,...wal.mergeProvenance?{resume:wal.mergeProvenance}:{},onBeforeMerge:async(provenance)=>{wal={...wal,mergeProvenance:provenance,observedFiles:observed2},await writeWal3(filePath,wal)},onMerged:async(mergedResult)=>{wal={...wal,state:"PREPARED",accepted:observed2.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed2)},await writeWal3(filePath,wal),recovered=await commitPrepared(directory,wal,{landedUnstaged:mergedResult.strategy==="squash-unstaged"})}});if(mergeResult.outcome!=="merged"||recovered===null){if(mergeResult.outcome==="failed"&&mergeResult.stage===SOURCE_WORKTREE_GONE_STAGE&&await selfHealMissingLaneWorktree(directory,filePath,taskId,wal.transitionId,descriptor,mergeResult.message))return null;throw Error(`CODER_SETTLEMENT_MERGE_RECOVERY_REQUIRED: transition ${wal.transitionId} for task ${taskId} worktree merge-back did not reach merged (${filePath}, state ${wal.state}, outcome ${mergeResult.outcome}${mergeResult.outcome==="failed"&&mergeResult.message?`: ${mergeResult.message}`:""}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`)}await cleanupRecoveredWorktree(directory,descriptor,{retainBranch:mergeResult.strategy==="squash-unstaged"});let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");return await writeWal3(filePath,{...committedWal,cleanupComplete:!0}),recovered}let rawObserved=await changedFilesSinceSnapshotAsync(directory,wal.context.baseline),observed;if(rawObserved===null){if(baselineAttributionDoomed(wal.context.baseline)){let aborted2=await abortDispatchedWalUnderLock(directory,taskId,wal.transitionId,doomedReason(wal.context.baseline));if(aborted2.outcome==="aborted"||aborted2.outcome==="already-aborted")return null}observed=null}else if(wal.context.declaredFiles===null)observed=[];else observed=rawObserved.filter((filePath2)=>isPathWithinDeclaredScope(filePath2,wal.context.declaredFiles??[],directory));if(observed===null)throw Error(`CODER_SETTLEMENT_RECOVERY_UNCERTAIN: transition ${wal.transitionId} for task ${taskId} workspace changes could not be attributed to the declared scope (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry; do not remove the WAL by hand.`);wal={...wal,state:"PREPARED",accepted:observed.length>0,testEngineerExempt:isMarkdownOnlyTaskChange(wal.context.declaredFiles,observed)},await writeWal3(filePath,wal)}let committed=await commitPrepared(directory,wal);if(wal.worktree){await cleanupRecoveredWorktree(directory,wal.worktree);let committedWal=await readWal2(filePath,taskId);if(committedWal===null)throw Error("CODER_SETTLEMENT_WAL_MISSING");await writeWal3(filePath,{...committedWal,cleanupComplete:!0})}return committed})}function releaseCoderDispatchOwnership(directory,taskId,transitionId){liveDispatches.delete(dispatchKey(directory,taskId,transitionId))}async function assertNoUnsettledCoderDispatch(directory,taskId){let filePath=walPath(directory,taskId),wal=await readWal2(filePath,taskId);if(wal===null)return;if(wal.state==="DISPATCHED"||wal.state==="PREPARED")throw Error(`CODER_SETTLEMENT_RECOVERY_REQUIRED: transition ${wal.transitionId} must settle before task ${taskId} can change plan status (${filePath}, state ${wal.state}). Run /swarm recover ${taskId} (or /swarm reset-session), then retry.`)}async function listCoderSettlementWalStates(directory){let entries;try{let dirPath=validateSwarmPath(directory,"coder-settlements");entries=await readdir6(dirPath)}catch{return{states:[],truncated:!1}}let matching=entries.filter((entry)=>SETTLEMENT_WAL_FILE_PATTERN.test(entry)),states=[];for(let entry of matching.sort().slice(0,MAX_SETTLEMENT_WAL_SCAN)){let taskId=entry.slice(0,-5);try{let wal=await readWal2(walPath(directory,taskId),taskId);if(wal===null)continue;states.push({taskId,state:wal.state,transitionId:wal.transitionId,processId:wal.processId,recordedAt:wal.recordedAt,accepted:wal.accepted===!0?!0:void 0,declaredFiles:wal.context?.declaredFiles??null,expectedGeneration:wal.expectedGeneration,ownedInProcess:liveDispatches.has(dispatchKey(directory,taskId,wal.transitionId)),ownedByLiveForeignPid:wal.processId!==process.pid&&isProcessAlive3(wal.processId)})}catch{states.push({taskId,state:"unreadable",ownedInProcess:!1,ownedByLiveForeignPid:!1})}}return{states,truncated:matching.length>MAX_SETTLEMENT_WAL_SCAN}}async function recoverStaleCoderSettlements(directory,options){let{states:listed,truncated}=await listCoderSettlementWalStates(directory),filter=options?.taskIds?new Set(options.taskIds):void 0,results=[];for(let entry of listed){if(filter&&!filter.has(entry.taskId))continue;if(entry.state==="unreadable"){results.push({taskId:entry.taskId,outcome:"unreadable_wal"});continue}if(entry.state==="ABORTED"||entry.state==="COMMITTED"){try{await _internals86.recoverCoderSettlement(directory,entry.taskId),results.push({taskId:entry.taskId,outcome:"already_terminal",state:entry.state})}catch(error49){results.push({taskId:entry.taskId,outcome:"error",message:error49 instanceof Error?error49.message:String(error49)})}continue}if(entry.ownedInProcess&&options?.force!==!0){results.push({taskId:entry.taskId,outcome:"owned_in_process",transitionId:entry.transitionId??""});continue}if(entry.ownedByLiveForeignPid){results.push({taskId:entry.taskId,outcome:"owned_by_live_foreign_pid",processId:entry.processId??-1});continue}let forced=entry.ownedInProcess&&options?.force===!0;if(forced&&entry.transitionId)releaseCoderDispatchOwnership(directory,entry.taskId,entry.transitionId),await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId,actor:"swarm-recovery"},{forced:!0,stage:"ownership-release"});try{let recovered=await _internals86.recoverCoderSettlement(directory,entry.taskId);if(recovered===null){let current=null;try{current=await readWal2(walPath(directory,entry.taskId),entry.taskId)}catch{current=null}if(current&&(current.state==="COMMITTED"||current.state==="ABORTED")){results.push({taskId:entry.taskId,outcome:"already_terminal",state:current.state});continue}results.push({taskId:entry.taskId,outcome:"error",message:"settlement WAL disappeared during recovery"});continue}await appendSettlementEvent(directory,"recovered",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,accepted:recovered.accepted,previousTransitionId:entry.transitionId??"",previousState:entry.state,...typeof entry.expectedGeneration==="number"?{expectedGeneration:entry.expectedGeneration}:{}}),results.push({taskId:entry.taskId,outcome:"recovered",accepted:recovered.accepted,forced})}catch(error49){let message=error49 instanceof Error?error49.message:String(error49);await appendSettlementEvent(directory,"recovery-failed",{taskId:entry.taskId,transitionId:entry.transitionId??"",actor:"swarm-recovery"},{forced,error:message}),results.push({taskId:entry.taskId,outcome:"error",message})}}return{results,truncated}}var LIVE_DISPATCHES_SYMBOL,globalRegistry2,liveDispatches,runtimeId,MAX_LIVE_DISPATCHES=512,MAX_SETTLEMENT_WAL_SCAN=200,SETTLEMENT_WAL_FILE_PATTERN,_internals86;var init_coder_settlement=__esm(()=>{init_workspace_snapshot();init_core_events();init_gate_evidence();init_gate_evidence_classification();init_worktree_provisioning_owner();init_utils2();init_file_locks();init_path_identity();init_warning_buffer();init_canonical_root();init_git_executable();init_logger();init_merge2();init_workflow_wal_file();LIVE_DISPATCHES_SYMBOL=Symbol.for("opencode-swarm.workflow.coder-settlement.live-dispatches"),globalRegistry2=globalThis;if(!globalRegistry2[LIVE_DISPATCHES_SYMBOL])globalRegistry2[LIVE_DISPATCHES_SYMBOL]=new Set;liveDispatches=globalRegistry2[LIVE_DISPATCHES_SYMBOL],runtimeId=randomUUID14();SETTLEMENT_WAL_FILE_PATTERN=/^[\w.\-:]+\.json$/;_internals86={liveDispatches,removeWorktreeProvisioningOwner,branchExists:probeBranchExists,recoverCoderSettlement}});var exports_pending_delegations={};__export(exports_pending_delegations,{writeDelegationFallback:()=>writeDelegationFallback,updateCoderSettlement:()=>updateCoderSettlement,sweepStaleDelegations:()=>sweepStaleDelegations,scanDelegationsForRecovery:()=>scanDelegationsForRecovery,scanDelegationFallbacksForRecovery:()=>scanDelegationFallbacksForRecovery,scanBackgroundCoderReservationsForAdmission:()=>scanBackgroundCoderReservationsForAdmission,reserveBackgroundCoderSlot:()=>reserveBackgroundCoderSlot,replacePendingBackgroundAdvisory:()=>replacePendingBackgroundAdvisory,removeDelegationFallback:()=>removeDelegationFallback,releasePreparedBackgroundAdvisories:()=>releasePreparedBackgroundAdvisories,releaseBackgroundCoderReservation:()=>releaseBackgroundCoderReservation,registerStaleSweepObserver:()=>registerStaleSweepObserver,registerLegacyCoderSettlementReconciler:()=>registerLegacyCoderSettlementReconciler,recordPendingDelegationDetailed:()=>recordPendingDelegationDetailed,recordPendingDelegation:()=>recordPendingDelegation,recordDelegationIngestionResult:()=>recordDelegationIngestionResult,readDelegationsDetailed:()=>readDelegationsDetailed,readDelegations:()=>readDelegations,readDelegationFallback:()=>readDelegationFallback,putPendingBackgroundAdvisory:()=>putPendingBackgroundAdvisory,publishPrReviewResultReceipt:()=>publishPrReviewResultReceipt,promoteDelegationFallback:()=>promoteDelegationFallback,preparePendingBackgroundAdvisories:()=>preparePendingBackgroundAdvisories,normalizeBackgroundObservedFiles:()=>normalizeBackgroundObservedFiles,markLegacyCoderSettlementTransferPending:()=>markLegacyCoderSettlementTransferPending,maintainBackgroundDelegations:()=>maintainBackgroundDelegations,listDelegationFallbacks:()=>listDelegationFallbacks,isUnsettledWorktreeOwner:()=>isUnsettledWorktreeOwner,isTerminalDelegationStatus:()=>isTerminalDelegationStatus,findOpenAsyncLaneBatches:()=>findOpenAsyncLaneBatches,findDelegationForCompletion:()=>findDelegationForCompletion,findByCorrelationIdDetailed:()=>findByCorrelationIdDetailed,findByCorrelationId:()=>findByCorrelationId,findByBatchIdDetailed:()=>findByBatchIdDetailed,findByBatchId:()=>findByBatchId,compactBackgroundDelegations:()=>compactBackgroundDelegations,clearLegacyCoderSettlementTransferPending:()=>clearLegacyCoderSettlementTransferPending,claimTerminalResult:()=>claimTerminalResult,claimDelegationIngestion:()=>claimDelegationIngestion,claimCoderSettlement:()=>claimCoderSettlement,buildPromptSnapshot:()=>buildPromptSnapshot,buildBackgroundCompletionEventId:()=>buildBackgroundCompletionEventId,buildBackgroundCoderReservationId:()=>buildBackgroundCoderReservationId,bindBackgroundCoderReservation:()=>bindBackgroundCoderReservation,appendDelegationTransition:()=>appendDelegationTransition,acknowledgeObservedBackgroundAdvisories:()=>acknowledgeObservedBackgroundAdvisories,_internals:()=>_internals87,_checkpointInternals:()=>_checkpointInternals,TOMBSTONE_MIN_AGE_MS:()=>TOMBSTONE_MIN_AGE_MS,MAX_RECOVERY_LEDGER_BYTES:()=>MAX_RECOVERY_LEDGER_BYTES,MAX_LIVE_BACKGROUND_FALLBACKS:()=>MAX_LIVE_BACKGROUND_FALLBACKS,MAX_LIVE_BACKGROUND_CODER_RESERVATIONS:()=>MAX_LIVE_BACKGROUND_CODER_RESERVATIONS,MAX_CHECKPOINT_RECORDS:()=>MAX_CHECKPOINT_RECORDS,MAX_CHECKPOINT_BYTES:()=>MAX_CHECKPOINT_BYTES,MAX_BACKGROUND_OBSERVED_FILES:()=>MAX_BACKGROUND_OBSERVED_FILES,MAX_BACKGROUND_ADVISORY_CHARS:()=>MAX_BACKGROUND_ADVISORY_CHARS,LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER:()=>LEGACY_CODER_SETTLEMENT_PENDING_ADVISORY_MARKER,DELEGATION_READ_RETRY_DELAY_MS:()=>DELEGATION_READ_RETRY_DELAY_MS,DELEGATION_COMPACTION_LOW_WATER_BYTES:()=>DELEGATION_COMPACTION_LOW_WATER_BYTES,DELEGATION_COMPACTION_HIGH_WATER_BYTES:()=>DELEGATION_COMPACTION_HIGH_WATER_BYTES,DEFAULT_SWEEPABLE_DELEGATION_STATUSES:()=>DEFAULT_SWEEPABLE_DELEGATION_STATUSES,DEFAULT_STALE_DELEGATION_TIMEOUT_MS:()=>DEFAULT_STALE_DELEGATION_TIMEOUT_MS,BACKGROUND_INGESTION_LEASE_MS:()=>BACKGROUND_INGESTION_LEASE_MS,BACKGROUND_DELEGATION_FALLBACK_DIR:()=>BACKGROUND_DELEGATION_FALLBACK_DIR,BACKGROUND_DELEGATIONS_MANIFEST_FILE:()=>BACKGROUND_DELEGATIONS_MANIFEST_FILE,BACKGROUND_DELEGATIONS_FILE:()=>BACKGROUND_DELEGATIONS_FILE,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE:()=>BACKGROUND_DELEGATIONS_CHECKPOINT_FILE,BACKGROUND_CODER_RESERVATION_LEASE_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MS,BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS,BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS:()=>BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS,BACKGROUND_CODER_RESERVATIONS_FILE:()=>BACKGROUND_CODER_RESERVATIONS_FILE});import{createHash as createHash45}from"node:crypto";import*as fs62 from"node:fs";import*as path96 from"node:path";import{isDeepStrictEqual}from"node:util";function clampReservationLeaseMs(leaseMs){if(leaseMs===void 0)return BACKGROUND_CODER_RESERVATION_LEASE_MS;if(!Number.isFinite(leaseMs))return BACKGROUND_CODER_RESERVATION_LEASE_MS;return Math.min(Math.max(Math.round(leaseMs),BACKGROUND_CODER_RESERVATION_LEASE_MIN_MS),BACKGROUND_CODER_RESERVATION_LEASE_MAX_MS)}function isValidReservationGeneration(generation){return generation===void 0||Number.isInteger(generation)&&generation>=1&&generation<=MAX_BACKGROUND_DELEGATION_GENERATION}function storePath5(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_FILE)}function checkpointPath2(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_CHECKPOINT_FILE)}function manifestPath(directory){return validateSwarmPath(directory,BACKGROUND_DELEGATIONS_MANIFEST_FILE)}function importedShadowPath2(filePath){return`${filePath}.imported`}function projectionMarkerPath2(filePath){return`${filePath}.sqlite-projection`}function coordinationReservationLeaseKey(reservation){return{namespace:RESERVATION_LEASE_NAMESPACE,entityKey:reservation.reservationId,generation:reservation.generation??1,ownerToken:reservation.reservationId}}function releaseReservationLeaseIfPresent(directory,reservation){let leaseKey=coordinationReservationLeaseKey(reservation),existing=getCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey);if(!existing)return;if(existing.generation!==leaseKey.generation||existing.ownerToken!==leaseKey.ownerToken||!releaseCoordinationLease(directory,leaseKey.namespace,leaseKey.entityKey,leaseKey.generation,leaseKey.ownerToken))throw Error(`reservation lease authority mismatch for ${reservation.reservationId}`)}function coordinationRowsToDelegations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=RecordSchema2.safeParse(JSON.parse(row.payload));if(!parsed.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(parsed.data.correlationId!==row.entityKey)throw Error(`delegation coordination row authority binding mismatch: payload correlationId does not equal entity key ${row.entityKey}`);if(Math.max(parsed.data.generation??1,1)!==row.generation)throw Error(`delegation coordination row authority binding mismatch: payload generation does not equal row generation for ${row.entityKey}`);if(parsed.data.status!==row.status)throw Error(`delegation coordination row authority binding mismatch: payload status does not equal row status for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.correlationId.localeCompare(right.correlationId):left.createdAt-right.createdAt)}catch(error49){return recordLedgerUncertainty(directory,error49 instanceof Error?error49.message:String(error49),"coordination-read"),null}}function archiveShadowFileBestEffort2(filePath){if(!fs62.existsSync(filePath))return;let importedPath=importedShadowPath2(filePath);try{if(fs62.existsSync(importedPath))return;fs62.renameSync(filePath,importedPath)}catch(error49){warn(`[background] shadow archive failed for ${path96.basename(filePath)}: ${error49 instanceof Error?error49.message:String(error49)}`)}}function writeDelegationShadowProjection(directory,records){ensureSwarmDir4(directory);let payload=records.map((record2)=>JSON.stringify(record2)).join(`
1265
1265
  `)+(records.length>0?`
1266
1266
  `:"");fs62.writeFileSync(storePath5(directory),payload,"utf-8"),fs62.writeFileSync(projectionMarkerPath2(storePath5(directory)),"","utf-8")}function loadLegacyDelegationsStrict(directory){let load=loadFoldedState(directory,{strict:!0});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"legacy-import",load.repairHint),null;return[...load.records.values()]}function delegationShadowMatches(directory,records){let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return!1;return isDeepStrictEqual([...load.records.values()].sort((left,right)=>left.correlationId.localeCompare(right.correlationId)),[...records].sort((left,right)=>left.correlationId.localeCompare(right.correlationId)))}function delegationShadowDigest(directory,records){let hash3=createHash45("sha256");hash3.update(JSON.stringify(records));for(let filePath of[storePath5(directory),checkpointPath2(directory),manifestPath(directory)]){if(!fs62.existsSync(filePath))continue;hash3.update(path96.basename(filePath)),hash3.update(fs62.readFileSync(filePath))}return hash3.digest("hex")}function ensureDelegationCoordinationImported(directory,createIfNeeded){let dbExists=projectDbExists(directory);if(!createIfNeeded&&!dbExists)return"absent";let existing=dbExists?coordinationRowsToDelegations(directory):null;if(dbExists&&existing===null)return"uncertain";if(existing&&existing.length>0){if(createIfNeeded)return"ready";if(!(fs62.existsSync(projectionMarkerPath2(storePath5(directory)))&&delegationShadowMatches(directory,existing))){for(let filePath of[storePath5(directory),checkpointPath2(directory),manifestPath(directory)])archiveShadowFileBestEffort2(filePath);writeDelegationShadowProjection(directory,existing)}return"ready"}let legacyRecords=loadLegacyDelegationsStrict(directory);if(legacyRecords===null)return"uncertain";if(legacyRecords.length===0&&!fs62.existsSync(storePath5(directory))&&!fs62.existsSync(checkpointPath2(directory))&&!fs62.existsSync(manifestPath(directory))){if(!createIfNeeded)return"absent";return withCoordinationTransaction(directory,()=>{return}),"ready"}if(importCoordinationOnce(directory,{source:BACKGROUND_DELEGATIONS_FILE,sourceDigest:delegationShadowDigest(directory,legacyRecords),rowCount:legacyRecords.length,emptyNamespace:DELEGATION_COORDINATION_NAMESPACE},()=>{for(let record2 of legacyRecords){let result=transitionCoordinationState(directory,{namespace:DELEGATION_COORDINATION_NAMESPACE,entityKey:record2.correlationId,expectedRevision:null,generation:Math.max(record2.generation??1,1),status:record2.status,payload:JSON.stringify(record2)});if(result.outcome!=="applied")throw Error(`delegation import failed for ${record2.correlationId}: ${result.outcome}`)}})==="imported")archiveShadowFileBestEffort2(storePath5(directory)),archiveShadowFileBestEffort2(checkpointPath2(directory)),archiveShadowFileBestEffort2(manifestPath(directory)),writeDelegationShadowProjection(directory,legacyRecords);return"ready"}function pruneCoordinationDelegationRows(directory){let terminals=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS).filter((row)=>!isCheckpointLiveRecord(JSON.parse(row.payload))).sort((left,right)=>left.updatedAt.localeCompare(right.updatedAt)),excessTerminals=Math.max(0,terminals.length-MAX_COORDINATION_TERMINAL_ROWS);for(let row of terminals.slice(0,excessTerminals))deleteCoordinationState(directory,DELEGATION_COORDINATION_NAMESPACE,row.entityKey,row.revision);if(listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS).length>=MAX_COORDINATION_DELEGATION_ROWS)throw Error(`delegation coordination state reached its ${MAX_COORDINATION_DELEGATION_ROWS}-row safety bound`)}function portableSyncSleep(ms){try{Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,ms)}catch{let start=Date.now();while(Date.now()-start<ms);}}function writeDurableFileSync(target,contents){let tmp=`${target}.tmp-${process.pid}-${Math.random().toString(36).slice(2,10)}`;try{let fd=fs62.openSync(tmp,"w");try{if(typeof contents==="string")fs62.writeSync(fd,contents);else fs62.writeSync(fd,contents,0,contents.length);fs62.fsyncSync(fd)}finally{fs62.closeSync(fd)}_checkpointInternals.renameWithRetry(tmp,target)}catch(err){try{fs62.rmSync(tmp,{force:!0})}catch{}throw err}try{let dfd=fs62.openSync(path96.dirname(target),"r");try{fs62.fsyncSync(dfd)}finally{fs62.closeSync(dfd)}}catch{}}function readJsonFileWithRetry(target){let raw;try{raw=fs62.readFileSync(target,"utf-8")}catch(err){let code=err.code;if(code==="ENOENT")return{status:"absent"};return{status:"invalid",reason:`unreadable (${code??"unknown error"})`}}try{return{status:"ok",value:JSON.parse(raw)}}catch(err){return{status:"invalid",reason:`malformed JSON (${err instanceof Error?err.message:String(err)})`}}}function readDelegationManifest(directory){let read=readJsonFileWithRetry(manifestPath(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=ManifestSchema.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"manifest fails schema validation"};return{kind:"ok",manifest:parsed.data}}function readDelegationCheckpoint(directory){let bytes=0;try{bytes=fs62.statSync(checkpointPath2(directory)).size}catch{}if(bytes>MAX_CHECKPOINT_BYTES)return{kind:"invalid",reason:`checkpoint exceeds the ${MAX_CHECKPOINT_BYTES}-byte bound`};let read=readJsonFileWithRetry(checkpointPath2(directory));if(read.status==="absent")return{kind:"absent"};if(read.status==="invalid")return{kind:"invalid",reason:read.reason};let parsed=CheckpointSchema2.safeParse(read.value);if(!parsed.success)return{kind:"invalid",reason:"checkpoint fails schema validation"};return{kind:"ok",checkpoint:parsed.data,bytes}}function sha256Hex(data){return createHash45("sha256").update(data).digest("hex")}function checkpointPayloadChecksum(checkpoint){return sha256Hex(JSON.stringify([checkpoint.schemaVersion,checkpoint.sequence,checkpoint.writerId,checkpoint.rootPath,checkpoint.createdAt,checkpoint.cutLedgerBytes,checkpoint.cutLedgerDigest,checkpoint.records,checkpoint.closed,checkpoint.audit]))}function loadFoldedState(directory,options){let manifestRead=readDelegationManifest(directory);if(manifestRead.kind==="invalid")return{status:"uncertain",reason:`background delegation manifest is invalid: ${manifestRead.reason}`,repairHint:CHECKPOINT_RESET_HINT};if(manifestRead.kind==="absent")return loadLegacyLedger(directory,options.strict);let manifest=manifestRead.manifest;if(!sameProjectRoot(manifest.rootPath,directory))return{status:"uncertain",reason:"background delegation checkpoint is bound to a different project root",repairHint:CHECKPOINT_REBIND_HINT};let checkpointRead=readDelegationCheckpoint(directory);if(checkpointRead.kind==="invalid"||checkpointRead.kind==="absent")return{status:"uncertain",reason:`background delegation checkpoint is invalid${checkpointRead.kind==="invalid"?`: ${checkpointRead.reason}`:" (file missing)"} while a manifest is published`,repairHint:CHECKPOINT_RESET_HINT};let checkpoint=checkpointRead.checkpoint;if(checkpoint.sequence!==manifest.sequence&&checkpoint.sequence!==manifest.sequence+1)return{status:"uncertain",reason:`background delegation checkpoint/manifest sequence mismatch (checkpoint ${checkpoint.sequence}, manifest ${manifest.sequence})`,repairHint:CHECKPOINT_RESET_HINT};if(checkpoint.sequence===manifest.sequence&&manifest.checkpointChecksum!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation manifest checksum does not match its checkpoint",repairHint:CHECKPOINT_RESET_HINT};if(checkpointPayloadChecksum(checkpoint)!==checkpoint.payloadChecksum)return{status:"uncertain",reason:"background delegation checkpoint payload checksum mismatch",repairHint:CHECKPOINT_RESET_HINT};let stat10;try{stat10=fs62.statSync(storePath5(directory))}catch(error49){return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let tail,mode;if(stat10.size>=checkpoint.cutLedgerBytes&&checkpoint.cutLedgerBytes>0){let prefix=readLedgerRegion(directory,0,checkpoint.cutLedgerBytes);if(sha256Hex(prefix)===checkpoint.cutLedgerDigest){let suffixBytes=stat10.size-checkpoint.cutLedgerBytes;if(suffixBytes>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};tail=suffixBytes===0?Buffer.alloc(0):readLedgerRegion(directory,checkpoint.cutLedgerBytes,suffixBytes),mode="checkpoint+ledger-suffix"}else tail=readBoundedRecentLedgerWindow(directory,stat10.size),mode="checkpoint+tail"}else tail=readBoundedRecentLedgerWindow(directory,stat10.size),mode="checkpoint+tail";let records=new Map;for(let record2 of checkpoint.records)records.set(record2.correlationId,record2);for(let summary of checkpoint.closed)records.set(summary.correlationId,summary);let lenientSkips=emptyLenientLedgerSkipCounts(),foldError=foldLedgerTail(records,tail,options.strict,checkpoint,lenientSkips);if(foldError)return{status:"uncertain",reason:foldError};if(!options.strict)recordLenientLedgerSkips(directory,mode,lenientSkips);return{status:"ok",mode,records,manifest,checkpoint}}function readLedgerRegion(directory,offset,length){let fd=fs62.openSync(storePath5(directory),"r");try{let buffer=Buffer.alloc(length),read=0;while(read<length){let n=fs62.readSync(fd,buffer,read,length-read,offset+read);if(n<=0)break;read+=n}return read===length?buffer:buffer.subarray(0,read)}finally{fs62.closeSync(fd)}}function readBoundedRecentLedgerWindow(directory,size){if(size===0)return Buffer.alloc(0);if(size<=MAX_RECOVERY_LEDGER_BYTES)return readLedgerRegion(directory,0,size);let window2=readLedgerRegion(directory,size-MAX_RECOVERY_LEDGER_BYTES,MAX_RECOVERY_LEDGER_BYTES),firstNewline=window2.indexOf(10);return firstNewline===-1?Buffer.alloc(0):window2.subarray(firstNewline+1)}function foldLedgerTail(records,tail,strict,checkpoint,lenientSkips){let lineNumber=0;for(let line of tail.toString("utf-8").split(`
1267
1267
  `)){lineNumber+=1;let trimmed=line.trim();if(!trimmed)continue;let parsedJson;try{parsedJson=JSON.parse(trimmed)}catch{if(strict)return`background delegation ledger has malformed JSON at line ${lineNumber}`;if(lenientSkips)lenientSkips.malformedJson+=1;continue}let parsed=RecordSchema2.safeParse(parsedJson);if(!parsed.success){if(strict)return`background delegation ledger has an invalid record at line ${lineNumber}`;if(lenientSkips)lenientSkips.invalidRecord+=1;continue}let existing=checkpoint?records.get(parsed.data.correlationId):void 0;if(checkpoint&&existing&&!(parsed.data.updatedAt>existing.updatedAt)&&!(parsed.data.updatedAt===existing.updatedAt&&parsed.data.updatedAt>checkpoint.createdAt))continue;records.set(parsed.data.correlationId,parsed.data)}return null}function loadLegacyLedger(directory,strict){if(!strict){let raw2;try{raw2=fs62.readFileSync(storePath5(directory),"utf-8")}catch(err){if(err.code!=="ENOENT")warn(`[background] readDelegations failed: ${err instanceof Error?err.message:String(err)}`);return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null}}let records2=new Map,lenientSkips=emptyLenientLedgerSkipCounts(),foldError2=foldLedgerTail(records2,Buffer.from(raw2,"utf-8"),!1,void 0,lenientSkips);return recordLenientLedgerSkips(directory,"legacy-ledger",lenientSkips),{status:"ok",mode:"legacy",records:records2,manifest:null,checkpoint:null}}let absolutePath;try{if(absolutePath=storePath5(directory),fs62.statSync(absolutePath).size>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger exceeds the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`}}catch(error49){if(error49.code==="ENOENT")return{status:"ok",mode:"legacy",records:new Map,manifest:null,checkpoint:null};return{status:"uncertain",reason:`background delegation ledger metadata is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}let raw;try{raw=fs62.readFileSync(absolutePath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background delegation ledger is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_LEDGER_BYTES)return{status:"uncertain",reason:`background delegation ledger changed beyond the ${MAX_RECOVERY_LEDGER_BYTES}-byte recovery bound`};let records=new Map,foldError=foldLedgerTail(records,Buffer.from(raw,"utf-8"),!0);if(foldError)return{status:"uncertain",reason:foldError};return{status:"ok",mode:"legacy",records,manifest:null,checkpoint:null}}function loadRecordsForWrite(directory){let importState=ensureDelegationCoordinationImported(directory,!0);if(importState==="uncertain")return null;if(importState==="ready"){let coordination=coordinationRowsToDelegations(directory);if(coordination!==null)return coordination;return null}let load=loadFoldedState(directory,{strict:!1});if(load.status==="uncertain")return recordLedgerUncertainty(directory,load.reason,"mutation",load.repairHint),null;return[...load.records.values()]}function findRecordForWrite(records,correlationId){if(!records)return null;for(let record2 of records)if(record2.correlationId===correlationId)return record2;return null}function recordLedgerUncertainty(directory,reason,source,repairHint){try{writeDelegationHealthArtifact(directory,{uncertainty:{reason,at:Date.now(),source,...repairHint?{repairHint}:{}}})}catch{}}function emptyLenientLedgerSkipCounts(){return{malformedJson:0,invalidRecord:0}}function shouldEmitLenientLedgerSignal(directory,signature){let key2=canonicalRootKeyFresh(directory),existing=lenientLedgerSignalByRoot.get(key2);if(existing===signature)return!1;if(!existing){if(lenientLedgerSignalOrder.length>=MAX_TRACKED_LENIENT_LEDGER_SIGNALS){let evicted=lenientLedgerSignalOrder.shift();if(evicted)lenientLedgerSignalByRoot.delete(evicted)}lenientLedgerSignalOrder.push(key2)}return lenientLedgerSignalByRoot.set(key2,signature),!0}function recordLenientLedgerSkips(directory,source,counts){let skipped=counts.malformedJson+counts.invalidRecord;if(skipped<=0)return;let reason=`background delegation ledger skipped ${skipped} malformed/invalid row${skipped===1?"":"s"} during lenient ${source} read (${counts.malformedJson} malformed JSON, ${counts.invalidRecord} invalid records)`,signature=`${source}:${counts.malformedJson}:${counts.invalidRecord}`;if(shouldEmitLenientLedgerSignal(directory,signature))criticalWarn(`[background] ${reason}`);try{let current=readDelegationHealthArtifact(directory);if(current?.lastUncertainty&&current.lastUncertainty.source!==LENIENT_LEDGER_SIGNAL_SOURCE)return;writeDelegationHealthArtifact(directory,{lastUncertainty:{reason,at:Date.now(),source:LENIENT_LEDGER_SIGNAL_SOURCE}})}catch{}}function isUnsettledWorktreeOwner(record2){return Boolean(record2.worktree)&&!(record2.coderSettlement?.state==="settled"&&record2.coderSettlement.outcome?.kind==="standard-worktree"&&(record2.coderSettlement.outcome.result==="merged"||record2.coderSettlement.outcome.result==="unchanged"))}function isCheckpointLiveRecord(record2){if(!isTerminal(record2.status))return!0;if(record2.advisoryInbox?.state==="pending")return!0;if(record2.legacyCoderSettlementTransfer)return!0;let settlement=record2.coderSettlement;if(settlement&&settlement.state!=="settled")return!0;if(settlement?.state==="settled"&&isUnsettledWorktreeOwner(record2))return!0;if(isActiveCoderOwner(record2))return!0;return!1}function buildClosedSummary(record2){let summary={...record2};if(delete summary.prompt,delete summary.taskChangeContext,summary.result)summary.result=stripResultBody(record2,summary.result);if(summary.terminalResult)summary.terminalResult={...summary.terminalResult,result:dropTerminalResultBody(summary.terminalResult.result)};let parsed=RecordSchema2.safeParse(summary);return parsed.success?parsed.data:null}function stripResultBody(record2,result){let{text:_text,error:_error,...rest}=result,receipt=parsePrReviewCollectionReceiptFooter(record2,result),shedMarker=receipt?null:parsePrReviewCollectionReceiptShedMarker(record2,result),receiptText=receipt?`${PR_REVIEW_COLLECTION_RECEIPT_PREFIX}${JSON.stringify(receipt)}`:shedMarker?`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(shedMarker)}`:void 0;return receiptText?{...rest,text:receiptText,outputPreviewChars:receiptText.length}:rest}function dropResultBody(result){let{text:_text,error:_error,outputPreviewChars:_preview,...rest}=result;return rest}function dropTerminalResultBody(result){let{prReviewResultReceipt:_receipt,...rest}=dropResultBody(result);return rest}function dropRetainedPrReviewReceipt(record2){let compact=(result)=>{let payload=parsePrReviewCollectionReceiptFooter(record2,result);if(!payload){let marker2=parsePrReviewCollectionReceiptShedMarker(record2,result);if(!marker2)return dropResultBody(result);let markerText=`${PR_REVIEW_COLLECTION_RECEIPT_SHED_PREFIX}${JSON.stringify(marker2)}`,{text:_text2,error:_error2,...rest2}=result;return{...rest2,text:markerText,outputPreviewChars:markerText.length}}let marker=encodePrReviewCollectionReceiptShedMarker(payload),{text:_text,error:_error,...rest}=result;return{...rest,text:marker,outputPreviewChars:marker.length}};return{...record2,...record2.result?{result:compact(record2.result)}:{},...record2.terminalResult?{terminalResult:{...record2.terminalResult,result:dropTerminalResultBody(record2.terminalResult.result)}}:{}}}function emptyAudit(){return{dispatchCount:0,terminalsByStatus:{completed:0,error:0,cancelled:0,stale:0},settledCount:0,preservedCount:0,lateTerminalCount:0,compactedTransitionCount:0,compactedRecordCount:0,firstDispatchAt:null,lastTerminalAt:null,lastCompactionAt:0}}function terminalEventStatusOf(record2){if(record2.terminalResult)return record2.terminalResult.status;if(record2.status==="completed"||record2.status==="error"||record2.status==="cancelled"||record2.status==="rejected"||record2.status==="stale")return record2.status;return null}function mergeCheckpointAudit(previous,previousCheckpoint,folded,healthLateTerminals,retiredLineCount,newlySummarizedCount,now){let prev=previous??emptyAudit(),prevById=new Map;if(previousCheckpoint){for(let record2 of previousCheckpoint.records)prevById.set(record2.correlationId,record2);for(let summary of previousCheckpoint.closed)prevById.set(summary.correlationId,summary)}let audit={dispatchCount:prev.dispatchCount,terminalsByStatus:{...prev.terminalsByStatus},settledCount:prev.settledCount,preservedCount:prev.preservedCount,lateTerminalCount:Math.max(prev.lateTerminalCount,healthLateTerminals),compactedTransitionCount:capCounter(prev.compactedTransitionCount,retiredLineCount),compactedRecordCount:capCounter(prev.compactedRecordCount,newlySummarizedCount),firstDispatchAt:prev.firstDispatchAt,lastTerminalAt:prev.lastTerminalAt,lastCompactionAt:now},minCreated=Number.POSITIVE_INFINITY,maxTerminal=0;for(let record2 of folded){let prevRecord=prevById.get(record2.correlationId);if(!prevRecord)audit.dispatchCount+=1;let terminalStatus=terminalEventStatusOf(record2);if(terminalStatus){if((prevRecord?terminalEventStatusOf(prevRecord):null)!==terminalStatus){if(terminalStatus!=="rejected")audit.terminalsByStatus[terminalStatus]+=1}maxTerminal=Math.max(maxTerminal,record2.terminalResult?.recordedAt??record2.completedAt??0)}if(record2.coderSettlement?.state==="settled"&&prevRecord?.coderSettlement?.state!=="settled")audit.settledCount+=1;if(record2.coderSettlement?.state==="preserved"&&prevRecord?.coderSettlement?.state!=="preserved")audit.preservedCount+=1;minCreated=Math.min(minCreated,record2.createdAt)}return audit.firstDispatchAt=Number.isFinite(minCreated)?Math.min(prev.firstDispatchAt??Number.POSITIVE_INFINITY,minCreated):prev.firstDispatchAt,audit.lastTerminalAt=Math.max(prev.lastTerminalAt??0,maxTerminal)||null,audit}function capCounter(previous,delta){return Number.isSafeInteger(previous+delta)?previous+delta:Number.MAX_SAFE_INTEGER}function synchronizeCoordinationAfterCompaction(directory,retained){if(!projectDbExists(directory))return;let retainedById=new Map(retained.map((record2)=>[record2.correlationId,record2]));withCoordinationTransaction(directory,()=>{let rows=listCoordinationStates(directory,DELEGATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`delegation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);for(let row of rows){let record2=retainedById.get(row.entityKey);if(!record2){if(!deleteCoordinationStateWithinTransaction(directory,DELEGATION_COORDINATION_NAMESPACE,row.entityKey,row.revision))throw Error(`coordination compaction delete lost a concurrent update for ${row.entityKey}`);continue}let current=RecordSchema2.safeParse(JSON.parse(row.payload));if(!current.success)throw Error(`delegation coordination row failed schema validation for ${row.entityKey}`);if(isDeepStrictEqual(current.data,record2))continue;if(getProjectDb(directory).run(`UPDATE coordination_state
@@ -1274,7 +1274,7 @@ ${warnings.map((w)=>`Detected signal: ${w}`).join(`
1274
1274
  `).some((entry)=>entry.trim()===advisory.message);return text.includes(advisory.message)}))continue;let next={...current,schemaVersion:current.schemaVersion===4?4:3,advisoryInbox:{...advisory,state:"delivered",deliveredAt:now,preparation:void 0},updatedAt:now};appendRecord2(directory,next),acknowledged+=1}if(acknowledged>0)maybeCompactDelegationsLocked(directory)}),acknowledged}catch(err){return warn(`[background] acknowledgeObservedBackgroundAdvisories failed: ${err instanceof Error?err.message:String(err)}`),0}}async function releasePreparedBackgroundAdvisories(directory,parentSessionId,preparationId,eventIds){return releaseBackgroundAdvisoryPreparation(directory,parentSessionId,preparationId,eventIds)}function findByBatchIdDetailed(directory,batchId,opts){if(!batchId)return{status:"ok",value:[]};let read=readDelegationsDetailed(directory);if(read.status==="uncertain")return read;return{status:"ok",value:read.records.filter((record2)=>record2.batchId===batchId&&(opts?.parentSessionId===void 0||record2.parentSessionId===opts.parentSessionId))}}function findByBatchId(directory,batchId,opts){let outcome=findByBatchIdDetailed(directory,batchId,opts);return outcome.status==="ok"?outcome.value:[]}function findOpenAsyncLaneBatches(directory){return readDelegations(directory).filter((record2)=>record2.batchId!==void 0&&(record2.status==="pending"||record2.status==="running"))}function isTerminal(status){return status==="completed"||status==="error"||status==="cancelled"||status==="stale"||status==="consumed"}function isTerminalDelegationStatus(status){return isTerminal(status)}function registerStaleSweepObserver(observer){_staleSweepObserver=observer}function sweepStaleLocked(directory,timeoutMs,now,statuses=DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={},limits={}){let swept=0,{excludeCorrelationIds,includeCorrelationIds}=filters,records=loadRecordsForWrite(directory);if(records===null)return 0;for(let record2 of records){if(limits.maxSweep!==void 0&&swept>=limits.maxSweep)break;if(includeCorrelationIds!==void 0&&!includeCorrelationIds.has(record2.correlationId))continue;if(excludeCorrelationIds?.has(record2.correlationId))continue;if(!statuses.has(record2.status))continue;if(now-record2.updatedAt<=timeoutMs)continue;let staleReason=`lane presumed stale after ${timeoutMs}ms without a terminal event`,livenessResult=record2.result?{...record2.result,workflowLaneFailureClass:"liveness"}:{error:staleReason,chars:staleReason.length,truncated:!1,digest:createHash45("sha256").update(staleReason).digest("hex"),workflowLaneFailureClass:"liveness"};appendRecord2(directory,{...record2,status:"stale",updatedAt:now,result:livenessResult});try{_staleSweepObserver?.(record2,"stale")}catch{}swept+=1}if(swept>0)maybeCompactDelegationsLocked(directory);return swept}async function sweepStaleDelegations(directory,timeoutMs,options={}){if(!timeoutMs||timeoutMs<=0)return 0;let statuses=options.statuses??DEFAULT_SWEEPABLE_DELEGATION_STATUSES,filters={excludeCorrelationIds:options.excludeCorrelationIds,includeCorrelationIds:options.includeCorrelationIds};try{return await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>sweepStaleLocked(directory,timeoutMs,Date.now(),statuses,filters))}catch(err){return warn(`[background] sweepStaleDelegations failed: ${err instanceof Error?err.message:String(err)}`),0}}function fallbackRelativePath(correlationId){let digest3=createHash45("sha256").update(correlationId).digest("hex");return path96.join(BACKGROUND_DELEGATION_FALLBACK_DIR,`${digest3}.json`)}function fallbackPath(directory,correlationId){return validateSwarmPath(directory,fallbackRelativePath(correlationId))}function fallbackDirectoryPath(directory){return path96.dirname(validateSwarmPath(directory,path96.join(BACKGROUND_DELEGATION_FALLBACK_DIR,".containment-anchor")))}function readFallbackDirectory(directory){return fs62.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0})}async function readFallbackFile(directory,correlationId){for(let attempt=0;attempt<5;attempt++)try{let raw=await fs62.promises.readFile(fallbackPath(directory,correlationId),"utf-8"),parsedJson=JSON.parse(raw),parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success||parsed.data.correlationId!==correlationId)return null;return parsed.data}catch(err){if(err.code==="ENOENT"&&attempt<4){await new Promise((resolve49)=>setTimeout(resolve49,10));continue}return null}return null}async function readDelegationFallback(directory,correlationId){if(!correlationId)return null;return readFallbackFile(directory,correlationId)}async function listDelegationFallbacks(directory){let entries;try{entries=_internals87.readFallbackDirectory(directory).sort((a,b)=>compareCodeUnits2(a.name,b.name)).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).slice(0,MAX_LIVE_BACKGROUND_FALLBACKS)}catch{return[]}let artifacts=[];for(let entry of entries)try{let raw=await fs62.promises.readFile(path96.join(fallbackDirectoryPath(directory),entry.name),"utf-8"),parsed=FallbackArtifactSchema.safeParse(JSON.parse(raw));if(parsed.success)artifacts.push(parsed.data)}catch{}return artifacts}async function scanDelegationFallbacksForRecovery(directory){let fallbackDir,entries;try{fallbackDir=fallbackDirectoryPath(directory),entries=_internals87.readFallbackDirectory(directory).sort((a,b)=>compareCodeUnits2(a.name,b.name)).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json"))}catch(error49){if(error49.code==="ENOENT")return{status:"ok",owners:[]};return{status:"uncertain",reason:`background fallback directory is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(entries.length>MAX_LIVE_BACKGROUND_FALLBACKS)return{status:"uncertain",reason:`background fallback owner count exceeds the ${MAX_LIVE_BACKGROUND_FALLBACKS}-artifact safety bound`};let artifacts=[];for(let entry of entries){let artifactPath=path96.join(fallbackDir,entry.name),raw;try{if(fs62.statSync(artifactPath).size>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" exceeds the recovery size bound`};raw=await fs62.promises.readFile(artifactPath,"utf-8")}catch(error49){return{status:"uncertain",reason:`background fallback artifact "${entry.name}" is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_RECOVERY_FALLBACK_BYTES)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" changed beyond the recovery size bound`};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has malformed JSON`}}let parsed=FallbackArtifactSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:`background fallback artifact "${entry.name}" has an invalid owner record`};artifacts.push(parsed.data)}return{status:"ok",owners:artifacts}}function countFallbackFiles(directory){try{return fs62.readdirSync(fallbackDirectoryPath(directory),{withFileTypes:!0}).filter((entry)=>entry.isFile()&&entry.name.endsWith(".json")).length}catch(err){if(err.code==="ENOENT")return 0;return MAX_LIVE_BACKGROUND_FALLBACKS}}async function writeDelegationFallback(directory,input,options={}){let now=Date.now(),record2={...buildPendingRecord(input,now),schemaVersion:3},artifact={schemaVersion:1,correlationId:input.correlationId,createdAt:now,record:record2},parsed=FallbackArtifactSchema.safeParse(artifact);if(!parsed.success)return null;let requestedCap=Math.floor(Math.max(1,options.maxLive??MAX_LIVE_BACKGROUND_FALLBACKS)),maxLive=Math.min(requestedCap,MAX_LIVE_BACKGROUND_FALLBACKS);try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT2,FALLBACK_LOCK_TASK,async()=>{let existing=await readFallbackFile(directory,input.correlationId);if(existing)return samePendingRecord(existing.record,parsed.data.record)?existing:null;if(countFallbackFiles(directory)>=maxLive)return null;let absPath=fallbackPath(directory,input.correlationId);return fs62.mkdirSync(path96.dirname(absPath),{recursive:!0}),await bunWrite(absPath,`${JSON.stringify(parsed.data)}
1275
1275
  `),parsed.data})}catch(err){return warn(`[background] writeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}async function removeDelegationFallback(directory,correlationId){if(!correlationId)return!1;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT2,FALLBACK_LOCK_TASK,async()=>{try{return await fs62.promises.unlink(fallbackPath(directory,correlationId)),!0}catch(err){return err.code==="ENOENT"}})}catch(err){return warn(`[background] removeDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),!1}}async function findDelegationForCompletion(directory,correlationId){if(!correlationId)return null;let primary=findByCorrelationIdDetailed(directory,correlationId);if(primary.status==="uncertain")return{source:"uncertain",record:null,uncertain:`delegation store unreadable after ${primary.attempts} attempts (${primary.reason})`};if(primary.value)return{source:"primary",record:primary.value};let fallback=await readDelegationFallback(directory,correlationId);return fallback?{source:"fallback",record:fallback.record,fallback}:null}function samePromotionIdentity(primary,fallback){return primary.correlationId===fallback.correlationId&&primary.subagentSessionId===fallback.subagentSessionId&&primary.parentSessionId===fallback.parentSessionId&&primary.callID===fallback.callID&&primary.planTaskId===fallback.planTaskId&&primary.coderReservationId===fallback.coderReservationId&&sameJson(primary.worktree??null,fallback.worktree??null)&&sameJson(primary.taskChangeContext??null,fallback.taskChangeContext??null)}function samePendingRecord(left,right){let{createdAt:_leftCreatedAt,updatedAt:_leftUpdatedAt,...leftIdentity}=left,{createdAt:_rightCreatedAt,updatedAt:_rightUpdatedAt,...rightIdentity}=right;return sameJson(leftIdentity,rightIdentity)}async function promoteDelegationFallback(directory,correlationId){if(!correlationId)return null;try{return await withEvidenceLock(directory,BACKGROUND_DELEGATION_FALLBACK_DIR,STORE_LOCK_AGENT2,FALLBACK_LOCK_TASK,async()=>{let fallback=await readFallbackFile(directory,correlationId);if(!fallback){let primary=findByCorrelationId(directory,correlationId);return primary?{source:"primary",record:primary}:null}let promoted=null;if(await withEvidenceLock(directory,BACKGROUND_DELEGATIONS_FILE,STORE_LOCK_AGENT2,STORE_LOCK_TASK2,async()=>{let records=loadRecordsForWrite(directory);if(records===null)return;let current=findRecordForWrite(records,correlationId);if(current){if(samePromotionIdentity(current,fallback.record))promoted=current;return}appendRecord2(directory,fallback.record),maybeCompactDelegationsLocked(directory),promoted=fallback.record}),!promoted)return null;try{await fs62.promises.unlink(fallbackPath(directory,correlationId))}catch(err){if(err.code!=="ENOENT")return null}return{source:"primary",record:promoted}})}catch(err){return warn(`[background] promoteDelegationFallback failed: ${err instanceof Error?err.message:String(err)}`),null}}function reservationStorePath(directory){return validateSwarmPath(directory,BACKGROUND_CODER_RESERVATIONS_FILE)}function reservationShadowDigest(directory,reservations){let hash3=createHash45("sha256");hash3.update(JSON.stringify(reservations));let filePath=reservationStorePath(directory);if(fs62.existsSync(filePath))hash3.update(fs62.readFileSync(filePath));return hash3.digest("hex")}function writeReservationShadowProjection(directory,reservations){let parsed=BackgroundCoderReservationStoreSchema.parse({schemaVersion:1,reservations});fs62.writeFileSync(reservationStorePath(directory),`${JSON.stringify(parsed)}
1276
1276
  `,"utf-8"),fs62.writeFileSync(projectionMarkerPath2(reservationStorePath(directory)),"","utf-8")}function coordinationRowsToReservations(directory){if(!projectDbExists(directory))return null;try{let rows=listCoordinationStates(directory,RESERVATION_COORDINATION_NAMESPACE,MAX_COORDINATION_STATE_LIST_ROWS);if(rows.length>=MAX_COORDINATION_STATE_LIST_ROWS)throw Error(`reservation coordination read reached its ${MAX_COORDINATION_STATE_LIST_ROWS}-row safety bound`);return rows.map((row)=>{let parsed=BackgroundCoderReservationSchema.safeParse(JSON.parse(row.payload));if(!parsed.success||parsed.data.reservationId!==row.entityKey||(parsed.data.generation??1)!==row.generation||parsed.data.state!==row.status)throw Error(`reservation coordination row failed schema or authority binding validation for ${row.entityKey}`);return parsed.data}).sort((left,right)=>left.createdAt===right.createdAt?left.reservationId.localeCompare(right.reservationId):left.createdAt-right.createdAt)}catch(error49){return recordLedgerUncertainty(directory,error49 instanceof Error?error49.message:String(error49),"reservation-coordination-read"),null}}function scanLegacyBackgroundCoderReservationsForAdmission(directory){let absolutePath,raw;try{if(absolutePath=reservationStorePath(directory),fs62.statSync(absolutePath).size>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:`background coder reservation store exceeds the ${MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES}-byte safety bound`};raw=fs62.readFileSync(absolutePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return{status:"ok",reservations:[]};return{status:"uncertain",reason:`background coder reservation store is unreadable: ${error49 instanceof Error?error49.message:String(error49)}`}}if(Buffer.byteLength(raw,"utf8")>MAX_BACKGROUND_CODER_RESERVATION_STORE_BYTES)return{status:"uncertain",reason:"background coder reservation store changed beyond its safety bound"};let parsedJson;try{parsedJson=JSON.parse(raw)}catch{return{status:"uncertain",reason:"background coder reservation store contains malformed JSON"}}let parsed=BackgroundCoderReservationStoreSchema.safeParse(parsedJson);if(!parsed.success)return{status:"uncertain",reason:"background coder reservation store failed strict schema validation"};return{status:"ok",reservations:parsed.data.reservations}}function ensureReservationCoordinationImported(directory,createIfNeeded){let dbExists=projectDbExists(directory);if(!createIfNeeded&&!dbExists)return"absent";let existing=dbExists?coordinationRowsToReservations(directory):null;if(dbExists&&existing===null)return"uncertain";if(existing&&existing.length>0){let legacy2=scanLegacyBackgroundCoderReservationsForAdmission(directory);if(!fs62.existsSync(projectionMarkerPath2(reservationStorePath(directory)))||legacy2.status!=="ok"||!isDeepStrictEqual(legacy2.reservations.sort((left,right)=>left.reservationId.localeCompare(right.reservationId)),[...existing].sort((left,right)=>left.reservationId.localeCompare(right.reservationId))))archiveShadowFileBestEffort2(reservationStorePath(directory));return writeReservationShadowProjection(directory,existing),"ready"}let legacy=scanLegacyBackgroundCoderReservationsForAdmission(directory);if(legacy.status==="uncertain")return recordLedgerUncertainty(directory,legacy.reason,"reservation-legacy-import"),"uncertain";if(legacy.reservations.length===0&&!fs62.existsSync(reservationStorePath(directory))){if(!createIfNeeded)return"absent";return withCoordinationTransaction(directory,()=>{return}),"ready"}if(importCoordinationOnce(directory,{source:BACKGROUND_CODER_RESERVATIONS_FILE,sourceDigest:reservationShadowDigest(directory,legacy.reservations),rowCount:legacy.reservations.length,emptyNamespace:RESERVATION_COORDINATION_NAMESPACE},()=>{for(let reservation of legacy.reservations){let result=transitionCoordinationState(directory,{namespace:RESERVATION_COORDINATION_NAMESPACE,entityKey:reservation.reservationId,expectedRevision:null,generation:reservation.generation??1,status:reservation.state,payload:JSON.stringify(reservation)});if(result.outcome!=="applied")throw Error(`reservation import failed for ${reservation.reservationId}: ${result.outcome}`);if(reservation.leaseExpiresAt!==void 0){let lease=acquireCoordinationLease(directory,{...coordinationReservationLeaseKey(reservation),leaseExpiresAt:new Date(reservation.leaseExpiresAt).toISOString(),payload:JSON.stringify({parentSessionId:reservation.parentSessionId,correlationId:reservation.correlationId})});if(lease.outcome==="held"||lease.outcome==="stale_generation")throw Error(`reservation lease import failed for ${reservation.reservationId}: ${lease.outcome}`)}}})==="imported")archiveShadowFileBestEffort2(reservationStorePath(directory)),writeReservationShadowProjection(directory,legacy.reservations);return"ready"}function buildBackgroundCoderReservationId(input){let ownerIdentity=input.planTaskId===null?["call",input.parentSessionId,input.callID]:["task",input.parentSessionId,input.planTaskId];return`bgcr1:${createHash45("sha256").update(JSON.stringify(ownerIdentity)).digest("hex")}`}function scanBackgroundCoderReservationsForAdmission(directory){let importState=ensureReservationCoordinationImported(directory,!1);if(importState==="uncertain")return{status:"uncertain",reason:"background coder reservation coordination state is uncertain"};if(importState==="ready"){let reservations=coordinationRowsToReservations(directory);if(reservations!==null)return{status:"ok",reservations};return{status:"uncertain",reason:"background coder reservation coordination state is unreadable or over-bound"}}return scanLegacyBackgroundCoderReservationsForAdmission(directory)}async function writeBackgroundCoderReservations(directory,reservations){let parsed=BackgroundCoderReservationStoreSchema.safeParse({schemaVersion:1,reservations});if(!parsed.success)return!1;let importState=ensureReservationCoordinationImported(directory,!0);if(importState==="uncertain")return!1;if(importState==="ready")try{return withCoordinationTransaction(directory,()=>{let safetyBound=_internals87.reservationCoordinationRowLimit,authoritativeCount=countCoordinationStates(directory,RESERVATION_COORDINATION_NAMESPACE);if(authoritativeCount>safetyBound)throw Error(`reservation coordination write exceeded its ${safetyBound}-row safety bound`);let currentRows=listCoordinationStates(directory,RESERVATION_COORDINATION_NAMESPACE,safetyBound);if(currentRows.length!==authoritativeCount)throw Error("reservation coordination state changed during bounded reconciliation");let current=new Map(currentRows.map((row)=>[row.entityKey,row])),nextIds=new Set(parsed.data.reservations.map((entry)=>entry.reservationId));for(let[reservationId,row]of current){if(nextIds.has(reservationId))continue;let currentReservation=BackgroundCoderReservationSchema.parse(JSON.parse(row.payload));if(!deleteCoordinationState(directory,RESERVATION_COORDINATION_NAMESPACE,reservationId,row.revision))throw Error(`reservation delete conflict for ${reservationId}`);releaseReservationLeaseIfPresent(directory,currentReservation)}for(let reservation of parsed.data.reservations){let row=current.get(reservation.reservationId),result=transitionCoordinationState(directory,{namespace:RESERVATION_COORDINATION_NAMESPACE,entityKey:reservation.reservationId,expectedRevision:row?.revision??null,generation:reservation.generation??1,status:reservation.state,payload:JSON.stringify(reservation),event:{streamId:reservation.reservationId,idempotencyKey:createHash45("sha256").update(JSON.stringify(reservation)).digest("hex"),eventType:reservation.state,payload:JSON.stringify(reservation)}});if(result.outcome!=="applied"&&result.outcome!=="duplicate")throw Error(`reservation write failed for ${reservation.reservationId}: ${result.outcome}`);let leaseKey=coordinationReservationLeaseKey(reservation);if(reservation.leaseExpiresAt!==void 0){let lease=acquireCoordinationLease(directory,{...leaseKey,leaseExpiresAt:new Date(reservation.leaseExpiresAt).toISOString(),payload:JSON.stringify({parentSessionId:reservation.parentSessionId,correlationId:reservation.correlationId})});if(lease.outcome==="held"||lease.outcome==="stale_generation")throw Error(`reservation lease write failed for ${reservation.reservationId}: ${lease.outcome}`)}else releaseReservationLeaseIfPresent(directory,reservation)}}),writeReservationShadowProjection(directory,parsed.data.reservations),!0}catch(error49){return warn(`[background] reservation coordination write failed: ${error49 instanceof Error?error49.message:String(error49)}`),!1}try{return await bunWrite(reservationStorePath(directory),`${JSON.stringify(parsed.data)}
1277
- `),!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,DELEGATION_READ_RETRY_DELAY_MS=25,MAX_TRACKED_DELEGATION_READ_UNCERTAIN_ROOTS=32,DELEGATION_READ_UNCERTAIN_EMIT_COOLDOWN_MS=60000,delegationReadUncertainEmitAtByRoot,delegationReadUncertainEmitOrder,DELEGATION_READ_REASON_MAX_CHARS=200,MAX_LEGACY_CODER_SETTLEMENT_RECONCILERS=32,RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES,legacyCoderSettlementReconcilers,legacyCoderSettlementReconcilerOrder,_internals87,_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_telemetry();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","liveness"]).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"]),landedUnstaged:exports_external.boolean().optional(),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)=>{fs62.renameSync(from,to)},syncSleep:portableSyncSleep};lenientLedgerSignalByRoot=new Map,lenientLedgerSignalOrder=[];delegationReadUncertainEmitAtByRoot=new Map,delegationReadUncertainEmitOrder=[];RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),legacyCoderSettlementReconcilers=new Map,legacyCoderSettlementReconcilerOrder=[];_internals87={readRetryDelayMs:DELEGATION_READ_RETRY_DELAY_MS,delegationReadUncertainEmitCooldownMs:DELEGATION_READ_UNCERTAIN_EMIT_COOLDOWN_MS,resetDelegationReadUncertainRegistry:()=>{delegationReadUncertainEmitAtByRoot.clear(),delegationReadUncertainEmitOrder.length=0},delegationReadUncertainEmitOrderSnapshot:()=>[...delegationReadUncertainEmitOrder],delegationReadUncertainCooldownsSnapshot:()=>new Map(delegationReadUncertainEmitAtByRoot),getLegacyCoderSettlementReconciler,readFallbackDirectory,getLegacyCoderSettlementReconcilerOrder:()=>[...legacyCoderSettlementReconcilerOrder],resetLegacyCoderSettlementReconcilers:()=>{legacyCoderSettlementReconcilers.clear(),legacyCoderSettlementReconcilerOrder.length=0},reservationCoordinationRowLimit:MAX_COORDINATION_STATE_LIST_ROWS,writeBackgroundCoderReservations}});import{createHash as createHash46}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 createHash46("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 fs63 from"node:fs";import*as path97 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 fs63.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path97.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path97.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path97.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path97.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;_internals88.warn(`external tool process kill failed for ${signal}`,error49)}function killProcess(proc){let signal=timeoutKillSignal(_internals88.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((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>resolve49(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals88.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>resolve49({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals88.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(!path97.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=_internals88.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((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>{if(exitSettled){resolve49({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve49({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve49)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve49({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)_internals88.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",_internals88;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;_internals88={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs,warn}});import*as fsp4 from"node:fs/promises";import*as path98 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:path98.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 fsp4.lstat(path98.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([_internals89.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals89.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals89.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 _internals89.activeOperations(path98.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,_internals89;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"]];_internals89={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash47}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=_internals90.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 createHash47("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,_internals90;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}];_internals90={currentAlgorithmVersion:FINGERPRINT_ALGORITHM_VERSION}});import{createHash as createHash48,randomUUID as randomUUID15}from"node:crypto";import*as fsp5 from"node:fs/promises";import*as path99 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=createHash48("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest3}`}function workflowGateStateRelativePath(sessionID){return path99.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function workflowGateStateLockRelativePath(sessionID){return path99.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowCheckoutMutationLockRelativePath(){return path99.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((resolve51)=>setTimeout(resolve51,ms))}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path99.normalize(path99.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}function stateCacheKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}\x00${normalizeSessionID(sessionID)}`}function rememberState(directory,state2){let cacheKey=stateCacheKey(directory,state2.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state2);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=path99.resolve(directory,".swarm"),parentPath=path99.dirname(path99.resolve(filePath)),relativeParent=path99.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path99.sep}`)||path99.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp5.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path99.sep).filter(Boolean)){let nextPath=path99.join(currentPath,segment);await hooks.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp5.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([fsp5.realpath(currentPath),fsp5.realpath(nextPath)]);if(normalizeComparableFsPath(path99.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp5.realpath(swarmRoot),realParent=await fsp5.realpath(parentPath),relativeRealParent=path99.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path99.sep}`)||path99.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat11=await fsp5.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([fsp5.lstat(filePath,{bigint:!0}),fsp5.realpath(path99.resolve(directory,".swarm")),fsp5.realpath(filePath),fsp5.realpath(path99.dirname(filePath))]),relativeFile=path99.relative(realRoot,realFile);if(stat11.isSymbolicLink()||!stat11.isFile()||!sameBigIntFileIdentity(stat11,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path99.sep}`)||path99.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 fsp5.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 fsp5.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 fsp5.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 readPrWorkflowGateStateCoordinationForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),row=getCoordinationStateRaw(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY);if(!row)return{kind:"absent"};if(row.payload.length>MAX_COORDINATION_PAYLOAD_CHARS)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload exceeds the maximum size"};let parsedJson;try{parsedJson=JSON.parse(row.payload)}catch{return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload is not valid JSON"}}let parsed=requireCodec().safeParse(parsedJson);if(!parsed.success)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload failed the workflow state schema"};if(parsed.data.sessionID!==normalizedSessionID)return{kind:"invalid",reason:"coordination payload session identity does not match the requested session"};if(parsed.data.revision!==row.generation)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload revision does not match its generation"};return{kind:"valid",rowRevision:row.revision,generation:row.generation,state:parsed.data}}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.sessionID!==normalizeSessionID(sessionID)||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(state2){let mode=state2.mode;return typeof mode==="string"&&mode.trim().length>0?mode:"active"}async function fileExists(filePath){try{return await fsp5.stat(filePath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeWorkflowGateState(state2){return JSON.stringify(state2,null,2)}async function readTextFileIfExists(filePath){try{return await fsp5.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker(directory,filePath){await ensurePrWorkflowSafeParentDirectory(directory,filePath),await fsp5.writeFile(filePath,`sqlite-projection
1277
+ `),!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,DELEGATION_READ_RETRY_DELAY_MS=25,MAX_TRACKED_DELEGATION_READ_UNCERTAIN_ROOTS=32,DELEGATION_READ_UNCERTAIN_EMIT_COOLDOWN_MS=60000,delegationReadUncertainEmitAtByRoot,delegationReadUncertainEmitOrder,DELEGATION_READ_REASON_MAX_CHARS=200,MAX_LEGACY_CODER_SETTLEMENT_RECONCILERS=32,RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES,legacyCoderSettlementReconcilers,legacyCoderSettlementReconcilerOrder,_internals87,_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_telemetry();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","liveness","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"]),landedUnstaged:exports_external.boolean().optional(),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)=>{fs62.renameSync(from,to)},syncSleep:portableSyncSleep};lenientLedgerSignalByRoot=new Map,lenientLedgerSignalOrder=[];delegationReadUncertainEmitAtByRoot=new Map,delegationReadUncertainEmitOrder=[];RETRYABLE_LEGACY_SETTLEMENT_ERROR_CODES=new Set(["CODER_SETTLEMENT_LOCKED","EACCES","EBUSY","EIO","EPERM","ETIMEDOUT"]),legacyCoderSettlementReconcilers=new Map,legacyCoderSettlementReconcilerOrder=[];_internals87={readRetryDelayMs:DELEGATION_READ_RETRY_DELAY_MS,delegationReadUncertainEmitCooldownMs:DELEGATION_READ_UNCERTAIN_EMIT_COOLDOWN_MS,resetDelegationReadUncertainRegistry:()=>{delegationReadUncertainEmitAtByRoot.clear(),delegationReadUncertainEmitOrder.length=0},delegationReadUncertainEmitOrderSnapshot:()=>[...delegationReadUncertainEmitOrder],delegationReadUncertainCooldownsSnapshot:()=>new Map(delegationReadUncertainEmitAtByRoot),getLegacyCoderSettlementReconciler,readFallbackDirectory,getLegacyCoderSettlementReconcilerOrder:()=>[...legacyCoderSettlementReconcilerOrder],resetLegacyCoderSettlementReconcilers:()=>{legacyCoderSettlementReconcilers.clear(),legacyCoderSettlementReconcilerOrder.length=0},reservationCoordinationRowLimit:MAX_COORDINATION_STATE_LIST_ROWS,writeBackgroundCoderReservations}});import{createHash as createHash46}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 createHash46("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 fs63 from"node:fs";import*as path97 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 fs63.statSync(candidate).isFile()}catch{return!1}}function resolveExecutableFromPath(names,envPath=process.env.PATH??"",platform=process.platform){let pathEntries=envPath.split(path97.delimiter).filter(Boolean),isWindows=platform==="win32";for(let rawName of names){if(!rawName)continue;if(path97.isAbsolute(rawName)&&isExecutableFile(rawName))return rawName;let extensions=isWindows&&path97.extname(rawName)===""?DEFAULT_WINDOWS_EXTENSIONS:[""];for(let dir of pathEntries)for(let ext of extensions){let candidate=path97.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;_internals88.warn(`external tool process kill failed for ${signal}`,error49)}function killProcess(proc){let signal=timeoutKillSignal(_internals88.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((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>resolve49(null),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals88.clearTimeout(timeoutHandle)}}async function waitForValueWithin(promise2,waitMs){let timeoutHandle;try{return await Promise.race([promise2.then((value)=>({completed:!0,value})),new Promise((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>resolve49({completed:!1}),waitMs)})])}finally{if(timeoutHandle!==void 0)_internals88.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(!path97.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=_internals88.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((resolve49)=>{timeoutHandle=_internals88.setTimeout(()=>{if(exitSettled){resolve49({kind:"exit",exitCode:settledExitCode??proc?.exitCode??0});return}resolve49({kind:"timeout"})},runnerTimeoutMs)}),cancelled=new Promise((resolve49)=>{if(!options.abortSignal)return;let handled=!1;if(abortListener=()=>{if(handled)return;handled=!0,resolve49({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)_internals88.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",_internals88;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;_internals88={bunSpawn,platform:()=>process.platform,now:()=>Date.now(),setTimeout,clearTimeout,clampTimeoutMs,computeSpawnTimeoutMs,warn}});import*as fsp4 from"node:fs/promises";import*as path98 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:path98.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 fsp4.lstat(path98.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([_internals89.runGitCapture(directory,["status","--porcelain=v2","--branch","-z","--untracked-files=all"]),_internals89.runGitCapture(directory,["rev-parse","--show-toplevel"]),_internals89.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 _internals89.activeOperations(path98.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,_internals89;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"]];_internals89={runGitCapture,activeOperations,parsePorcelainV2:parsePorcelainV2Snapshot}});import{createHash as createHash47}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=_internals90.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 createHash47("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,_internals90;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}];_internals90={currentAlgorithmVersion:FINGERPRINT_ALGORITHM_VERSION}});import{createHash as createHash48,randomUUID as randomUUID15}from"node:crypto";import*as fsp5 from"node:fs/promises";import*as path99 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=createHash48("sha256").update(normalized).digest("hex").slice(0,12);return`${slug}-${digest3}`}function workflowGateStateRelativePath(sessionID){return path99.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.json`)}function workflowGateStateLockRelativePath(sessionID){return path99.join(WORKFLOW_GATE_DIR,`${prWorkflowSessionFileStem(sessionID)}.lock`)}function workflowCheckoutMutationLockRelativePath(){return path99.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((resolve51)=>setTimeout(resolve51,ms))}function sameBigIntFileIdentity(left,right){return left.dev===right.dev&&left.ino===right.ino}function normalizeComparableFsPath(value){let normalized=path99.normalize(path99.resolve(value));return process.platform==="win32"?normalized.toLowerCase():normalized}function stateCacheKey(directory,sessionID){return`${canonicalRootKeyFresh(directory)}\x00${normalizeSessionID(sessionID)}`}function rememberState(directory,state2){let cacheKey=stateCacheKey(directory,state2.sessionID);trackedStatesByProjectSession.delete(cacheKey),trackedStatesByProjectSession.set(cacheKey,state2);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=path99.resolve(directory,".swarm"),parentPath=path99.dirname(path99.resolve(filePath)),relativeParent=path99.relative(swarmRoot,parentPath);if(relativeParent===".."||relativeParent.startsWith(`..${path99.sep}`)||path99.isAbsolute(relativeParent))throw Error("BLOCKED: PR workflow atomic destination escapes the project .swarm directory");await fsp5.mkdir(swarmRoot,{recursive:!0});let currentPath=swarmRoot,currentIdentity=await assertSafeDirectory(currentPath,void 0);for(let segment of relativeParent.split(path99.sep).filter(Boolean)){let nextPath=path99.join(currentPath,segment);await hooks.beforeSafeDirectoryCreate?.(currentPath,nextPath),await assertSafeDirectory(currentPath,currentIdentity);try{await fsp5.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([fsp5.realpath(currentPath),fsp5.realpath(nextPath)]);if(normalizeComparableFsPath(path99.dirname(realNext))!==normalizeComparableFsPath(realCurrent))throw Error("BLOCKED: PR workflow directory creation escaped the project .swarm tree");currentPath=nextPath,currentIdentity=nextIdentity}let realRoot=await fsp5.realpath(swarmRoot),realParent=await fsp5.realpath(parentPath),relativeRealParent=path99.relative(realRoot,realParent);if(relativeRealParent===".."||relativeRealParent.startsWith(`..${path99.sep}`)||path99.isAbsolute(relativeRealParent))throw Error("BLOCKED: PR workflow atomic parent escapes the project .swarm directory");return realParent}async function assertSafeDirectory(directoryPath,expectedIdentity){let stat11=await fsp5.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([fsp5.lstat(filePath,{bigint:!0}),fsp5.realpath(path99.resolve(directory,".swarm")),fsp5.realpath(filePath),fsp5.realpath(path99.dirname(filePath))]),relativeFile=path99.relative(realRoot,realFile);if(stat11.isSymbolicLink()||!stat11.isFile()||!sameBigIntFileIdentity(stat11,expectedIdentity)||normalizeComparableFsPath(realParent)!==normalizeComparableFsPath(expectedParent)||relativeFile===""||relativeFile===".."||relativeFile.startsWith(`..${path99.sep}`)||path99.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 fsp5.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 fsp5.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 fsp5.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 readPrWorkflowGateStateCoordinationForRecovery(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID),row=getCoordinationStateRaw(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY);if(!row)return{kind:"absent"};if(row.payload.length>MAX_COORDINATION_PAYLOAD_CHARS)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload exceeds the maximum size"};let parsedJson;try{parsedJson=JSON.parse(row.payload)}catch{return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload is not valid JSON"}}let parsed=requireCodec().safeParse(parsedJson);if(!parsed.success)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload failed the workflow state schema"};if(parsed.data.sessionID!==normalizedSessionID)return{kind:"invalid",reason:"coordination payload session identity does not match the requested session"};if(parsed.data.revision!==row.generation)return{kind:"corrupt",rowRevision:row.revision,generation:row.generation,reason:"coordination payload revision does not match its generation"};return{kind:"valid",rowRevision:row.revision,generation:row.generation,state:parsed.data}}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.sessionID!==normalizeSessionID(sessionID)||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(state2){let mode=state2.mode;return typeof mode==="string"&&mode.trim().length>0?mode:"active"}async function fileExists(filePath){try{return await fsp5.stat(filePath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeWorkflowGateState(state2){return JSON.stringify(state2,null,2)}async function readTextFileIfExists(filePath){try{return await fsp5.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker(directory,filePath){await ensurePrWorkflowSafeParentDirectory(directory,filePath),await fsp5.writeFile(filePath,`sqlite-projection
1278
1278
  `,"utf8")}async function renameWithRetry6(from,to){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await hooks.rename(from,to);return}catch(error49){lastError=error49;let code=error49.code;if(code!=="EEXIST"&&code!=="EPERM"&&code!=="EBUSY")throw error49;if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}throw lastError}async function collisionSafeImportedPath(filePath){let canonical=`${filePath}.imported`;if(!await fileExists(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!await fileExists(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path99.basename(filePath)}`)}async function archiveShadowSource(filePath){if(!await fileExists(filePath))return;await renameWithRetry6(filePath,await collisionSafeImportedPath(filePath))}async function syncWorkflowGateShadowProjection(directory,sessionID,state2,options){let filePath=workflowGateStatePath(directory,sessionID);if(options.archiveLegacy&&await fileExists(filePath))await archiveShadowSource(filePath);await writeAtomicJson2(directory,filePath,state2),await writeProjectionMarker(directory,workflowGateStateProjectionMarkerPath(directory,sessionID))}async function repairImportedWorkflowGateShadow(directory,sessionID,state2){let filePath=workflowGateStatePath(directory,sessionID),markerPath=workflowGateStateProjectionMarkerPath(directory,sessionID),live=await readTextFileIfExists(filePath);if(live===null){await syncWorkflowGateShadowProjection(directory,sessionID,state2,{archiveLegacy:!1});return}let canonicalImportedExists=await fileExists(workflowGateStateImportedPath(directory,sessionID)),markerExists=await fileExists(markerPath),projected=serializeWorkflowGateState(state2);if(canonicalImportedExists&&markerExists&&live===projected)return;if(canonicalImportedExists&&live===projected){await writeProjectionMarker(directory,markerPath);return}await syncWorkflowGateShadowProjection(directory,sessionID,state2,{archiveLegacy:!0})}async function removeWorkflowGateShadowProjection(directory,sessionID){for(let filePath of[workflowGateStatePath(directory,sessionID),workflowGateStateProjectionMarkerPath(directory,sessionID)])try{await(hooks.removeShadowProjection??((target)=>fsp5.rm(target,{force:!0})))(filePath)}catch(error49){if(error49.code!=="ENOENT")throw error49}}function appendSessionTerminalizationEvent(directory,sessionID,rowRevision){try{appendCoreEventSync(directory,{type:"pr_workflow_session_terminalized",timestamp:isoNow(),sessionID,rowRevision})}catch{}}async function importLegacyPrWorkflowGateStateIfNeeded(directory,sessionID,allowSalvagedImport=!1){let filePath=workflowGateStatePath(directory,sessionID),raw;try{raw=await fsp5.readFile(filePath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let legacy=allowSalvagedImport?(await(await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate))).readPrWorkflowGateStateForRecovery(directory,sessionID))?.state??null:await readPrWorkflowGateStateFileFromDisk(filePath,sessionID);if(!legacy)return null;let namespace=workflowGateStateCoordinationNamespace(sessionID),outcome=importCoordinationOnce(directory,{source:workflowGateStateRelativePath(sessionID),sourceDigest:createHash48("sha256").update(raw).digest("hex"),rowCount:1,emptyNamespace:namespace},()=>{let result=transitionCoordinationState(directory,{namespace,entityKey:WORKFLOW_STATE_ENTITY_KEY,expectedRevision:null,generation:legacy.revision,status:workflowStateStatus(legacy),payload:JSON.stringify(legacy)});if(result.outcome!=="applied")throw Error(`PR workflow gate state import failed: ${result.outcome}`)}),authoritative=await readPrWorkflowGateStateFromCoordination(directory,sessionID);if(authoritative&&outcome==="imported")await syncWorkflowGateShadowProjection(directory,sessionID,authoritative,{archiveLegacy:!0});return authoritative}async function writeStateWhileLocked(directory,state2,options={}){let bound=requireCodec(),validated=bound.parse(state2),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,validated.sessionID),current=currentAuthoritative?.state??null;if(!current)current=await readPrWorkflowGateStateFromDisk(directory,validated.sessionID),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,validated.sessionID);if(current?current.revision!==validated.revision:validated.revision!==0)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");if(current?.workflowInstanceId&&validated.workflowInstanceId!==current.workflowInstanceId&&options.replaceWorkflowInstanceId!==current.workflowInstanceId)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let nextState=bound.parse({...validated,revision:validated.revision+1});if(transitionCoordinationState(directory,{namespace:workflowGateStateCoordinationNamespace(validated.sessionID),entityKey:WORKFLOW_STATE_ENTITY_KEY,expectedRevision:currentAuthoritative?.rowRevision??null,generation:nextState.revision,status:workflowStateStatus(nextState),payload:JSON.stringify(nextState)}).outcome!=="applied")throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");return await syncWorkflowGateShadowProjection(directory,validated.sessionID,nextState,{archiveLegacy:!1}),rememberState(directory,nextState),nextState}async function deleteStateWhileLocked(directory,sessionID,options={}){let normalizedSessionID=normalizeSessionID(sessionID),currentAuthoritative=null,corruptCoordinationRowRevision;if(options.allowSalvagedRead){let coordination=readPrWorkflowGateStateCoordinationForRecovery(directory,normalizedSessionID);if(coordination.kind==="invalid")throw Error(`BLOCKED: PR workflow gate state for session "${normalizedSessionID}" is invalid (${coordination.reason})`);if(coordination.kind==="valid")currentAuthoritative={rowRevision:coordination.rowRevision,state:coordination.state};else if(coordination.kind==="corrupt")corruptCoordinationRowRevision=coordination.rowRevision}else currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,normalizedSessionID);let recoveryState=null;if(!currentAuthoritative){if(options.allowSalvagedRead){let{readPrWorkflowGateStateForRecovery}=await Promise.resolve().then(() => (init_pr_workflow_gate(),exports_pr_workflow_gate));recoveryState=(await readPrWorkflowGateStateForRecovery(directory,normalizedSessionID))?.state??null}if(!recoveryState)await readPrWorkflowGateStateFromDisk(directory,normalizedSessionID,{allowSalvagedImport:options.allowSalvagedRead===!0}),currentAuthoritative=readPrWorkflowGateStateCoordinationRow(directory,normalizedSessionID)}let currentRevision=currentAuthoritative?.state.revision??recoveryState?.revision;if(options.expectedStateRevision!==void 0&&currentRevision!==options.expectedStateRevision)throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying");let authoritativeRowRevision=currentAuthoritative?.rowRevision??(recoveryState?corruptCoordinationRowRevision:void 0);if(authoritativeRowRevision!==void 0){if(!deleteCoordinationState(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY,authoritativeRowRevision))throw Error("BLOCKED: PR workflow gate state changed concurrently; reload the active session state before retrying")}await removeWorkflowGateShadowProjection(directory,normalizedSessionID),forgetTrackedPrWorkflowState(directory,normalizedSessionID)}async function terminalizePrWorkflowGateForSession(directory,sessionID){let normalizedSessionID=normalizeSessionID(sessionID);await withSessionStateMutation(directory,normalizedSessionID,async()=>{let row=getCoordinationStateRaw(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY);if(await removeWorkflowGateShadowProjection(directory,normalizedSessionID),await hooks.beforeTerminalizationDelete?.(),row){if(!deleteCoordinationState(directory,workflowGateStateCoordinationNamespace(normalizedSessionID),WORKFLOW_STATE_ENTITY_KEY,row.revision))throw Error("BLOCKED: PR workflow gate state changed concurrently; retry session terminalization");appendSessionTerminalizationEvent(directory,normalizedSessionID,row.revision)}forgetTrackedPrWorkflowState(directory,normalizedSessionID)})}function checkoutMutationProjectKey(directory){return canonicalRootKeyFresh(directory)}async function withCheckoutMutationDeadline(promise2,phase){let timeout;try{return await Promise.race([promise2,new Promise((resolve51)=>{timeout=setTimeout(()=>{resolve51({status:"timeout",error:new PrWorkflowCheckoutMutationTimeoutError(phase)})},hooks.checkoutMutationActionTimeoutMs)})])}finally{if(timeout)clearTimeout(timeout)}}async function withPrWorkflowCheckoutMutationLock(directory,action){let key2=checkoutMutationProjectKey(directory),previous=pendingCheckoutMutationsByProject.get(key2)??Promise.resolve(),release,current=new Promise((resolve51)=>{release=resolve51}),queued=previous.then(()=>current);pendingCheckoutMutationsByProject.set(key2,queued);let previousResult=await withCheckoutMutationDeadline(previous.then(()=>({status:"ready"})),"queue");if(previousResult.status==="timeout")throw release(),queued.then(()=>{if(pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}),previousResult.error;let lock;try{lock=await acquireCheckoutMutationLock(directory)}catch(error49){if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2);throw error49}let actionOutcome=Promise.resolve().then(action).then((value)=>({status:"fulfilled",value}),(error49)=>({status:"rejected",error:error49})),outcome=await withCheckoutMutationDeadline(actionOutcome,"action");if(outcome.status==="timeout")throw actionOutcome.then(async()=>{try{await releaseCheckoutMutationLock(lock)}catch{}finally{if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}}),outcome.error;try{if(outcome.status==="rejected")throw outcome.error;return outcome.value}finally{try{await releaseCheckoutMutationLock(lock)}finally{if(release(),pendingCheckoutMutationsByProject.get(key2)===queued)pendingCheckoutMutationsByProject.delete(key2)}}}async function acquireCheckoutMutationLock(directory){let lockPath=workflowCheckoutMutationLockPath(directory),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await hooks.openCheckoutLock(lockPath),lock={ownerToken:randomUUID15(),pid:process.pid,createdAtMs:hooks.nowMs()},lockIdentity,writeError;try{let openedStat=await handle.stat({bigint:!0});lockIdentity={dev:openedStat.dev,ino:openedStat.ino},lockIdentity=await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow checkout mutation lock"),await hooks.beforeCheckoutLockWrite?.(),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError){if(lockIdentity)await removeCheckoutMutationLockByIdentity(directory,lockPath,lockIdentity,verifiedParent);throw writeError}return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedCheckoutMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow checkout mutation is being handled by another process; retry after that checkout settles")}async function releaseCheckoutMutationLock(lock){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++){try{if(await removeCheckoutMutationLockIfOwned(lock.path,lock.ownerToken)){completedCheckoutLockOwners.delete(lock.path);return}lastError=Error("PR workflow checkout mutation lock ownership changed before release")}catch(error49){lastError=error49}if(attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}throw rememberCompletedCheckoutLockOwner(lock.path,lock.ownerToken),lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock release failed")}async function reclaimAbandonedCheckoutMutationLock(lockPath){let lock=await readCheckoutMutationLock(lockPath);if(lock){if(lock.pid===process.pid&&completedCheckoutLockOwners.get(lockPath)===lock.ownerToken){let removed=await removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken);if(removed)completedCheckoutLockOwners.delete(lockPath);return removed}if(hooks.isProcessAlive(lock.pid))return!1;return removeCheckoutMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp5.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp5.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readCheckoutMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeCheckoutMutationLockIfOwned(lockPath,ownerToken){let lock=await readCheckoutMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await hooks.removeCheckoutLock(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}async function removeCheckoutMutationLockByIdentity(directory,lockPath,identity,verifiedParent){let lastError;for(let attempt=0;attempt<WINDOWS_RENAME_MAX_RETRIES3;attempt++)try{await assertClosedSwarmFileIdentity(directory,lockPath,identity,verifiedParent,"PR workflow checkout mutation lock"),await hooks.removeCheckoutLock(lockPath);return}catch(error49){if(error49.code==="ENOENT")return;if(lastError=error49,attempt<WINDOWS_RENAME_MAX_RETRIES3-1)await delay(RENAME_RETRY_DELAY_MS3)}throw lastError instanceof Error?lastError:Error("PR workflow checkout mutation lock cleanup failed")}function rememberCompletedCheckoutLockOwner(lockPath,ownerToken){completedCheckoutLockOwners.delete(lockPath),completedCheckoutLockOwners.set(lockPath,ownerToken);while(completedCheckoutLockOwners.size>MAX_COMPLETED_CHECKOUT_LOCK_OWNERS){let oldest=completedCheckoutLockOwners.keys().next().value;if(oldest===void 0)break;completedCheckoutLockOwners.delete(oldest)}}async function withSessionStateMutation(directory,sessionID,action){let key2=stateCacheKey(directory,sessionID),previous=pendingStateMutationsByProjectSession.get(key2)??Promise.resolve(),release,current=new Promise((resolve51)=>{release=resolve51}),queued=previous.then(()=>current);pendingStateMutationsByProjectSession.set(key2,queued),await previous;try{let lock=await acquireSessionStateMutationLock(directory,sessionID);try{return await action()}finally{await releaseSessionStateMutationLock(lock)}}finally{if(release(),pendingStateMutationsByProjectSession.get(key2)===queued)pendingStateMutationsByProjectSession.delete(key2)}}async function acquireSessionStateMutationLock(directory,sessionID){let lockPath=workflowGateStateLockPath(directory,sessionID),verifiedParent=await ensurePrWorkflowSafeParentDirectory(directory,lockPath);for(let attempt=0;attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS;attempt++)try{let handle=await fsp5.open(lockPath,"wx"),lock={ownerToken:randomUUID15(),pid:process.pid,createdAtMs:hooks.nowMs()},writeError;try{await hooks.beforeSessionStateLockWrite?.(),await assertOpenedSwarmFileIdentity(directory,lockPath,handle,verifiedParent,"PR workflow state mutation lock"),await handle.writeFile(JSON.stringify(lock),"utf-8")}catch(error49){writeError=error49}finally{await handle.close().catch(()=>{return})}if(writeError)throw await removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken),writeError;return{path:lockPath,ownerToken:lock.ownerToken}}catch(error49){if(error49.code!=="EEXIST")throw error49;if(await reclaimAbandonedSessionStateMutationLock(lockPath))continue;if(attempt<STATE_MUTATION_LOCK_MAX_ATTEMPTS-1)await delay(STATE_MUTATION_LOCK_RETRY_DELAY_MS)}throw Error("BLOCKED: PR workflow gate state is being mutated by another process; retry after that session transition finishes")}async function releaseSessionStateMutationLock(lock){try{await removeSessionStateMutationLockIfOwned(lock.path,lock.ownerToken)}catch{}}async function reclaimAbandonedSessionStateMutationLock(lockPath){let lock=await readSessionStateMutationLock(lockPath);if(lock){if(hooks.isProcessAlive(lock.pid))return!1;return removeSessionStateMutationLockIfOwned(lockPath,lock.ownerToken)}try{let stat11=await fsp5.stat(lockPath);if(hooks.nowMs()-stat11.mtimeMs<STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS)return!1;return await fsp5.rm(lockPath,{force:!0}),!0}catch(error49){if(error49.code==="ENOENT")return!0;throw error49}}async function readSessionStateMutationLock(lockPath){let raw;try{raw=await fsp5.readFile(lockPath,"utf-8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}try{let parsed=JSON.parse(raw);if(typeof parsed==="object"&&parsed!==null&&typeof parsed.ownerToken==="string"&&parsed.ownerToken.length>0&&typeof parsed.pid==="number"&&Number.isInteger(parsed.pid)&&parsed.pid>0&&typeof parsed.createdAtMs==="number"&&Number.isFinite(parsed.createdAtMs))return parsed}catch{}return null}async function removeSessionStateMutationLockIfOwned(lockPath,ownerToken){let lock=await readSessionStateMutationLock(lockPath);if(!lock||lock.ownerToken!==ownerToken)return!1;try{return await fsp5.rm(lockPath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}var WORKFLOW_GATE_DIR="pr-workflow-gates",WORKFLOW_STATE_COORDINATION_PREFIX="pr-workflow.state",WORKFLOW_STATE_ENTITY_KEY="state",MAX_TRACKED_SESSIONS2=200,MAX_COMPLETED_CHECKOUT_LOCK_OWNERS=64,WINDOWS_RENAME_MAX_RETRIES3=3,RENAME_RETRY_DELAY_MS3=10,STATE_MUTATION_LOCK_MAX_ATTEMPTS=50,STATE_MUTATION_LOCK_RETRY_DELAY_MS=10,STATE_MUTATION_LOCK_UNINITIALIZED_STALE_MS=30000,CHECKOUT_MUTATION_ACTION_TIMEOUT_MS=300000,MAX_COORDINATION_PAYLOAD_CHARS=1048576,trackedStatesByProjectSession,pendingStateMutationsByProjectSession,pendingCheckoutMutationsByProject,completedCheckoutLockOwners,defaultPersistenceHooks,hooks,codec2,PrWorkflowCheckoutMutationTimeoutError;var init_persistence=__esm(()=>{init_coordination_store();init_core_events();init_utils2();init_canonical_root();trackedStatesByProjectSession=new Map,pendingStateMutationsByProjectSession=new Map,pendingCheckoutMutationsByProject=new Map,completedCheckoutLockOwners=new Map;defaultPersistenceHooks={nowMs:()=>Date.now(),isProcessAlive:defaultIsProcessAlive,openCheckoutLock:(lockPath)=>fsp5.open(lockPath,"wx"),removeCheckoutLock:(lockPath)=>fsp5.rm(lockPath),checkoutMutationActionTimeoutMs:CHECKOUT_MUTATION_ACTION_TIMEOUT_MS,rename:(from,to)=>fsp5.rename(from,to)},hooks=defaultPersistenceHooks;PrWorkflowCheckoutMutationTimeoutError=class PrWorkflowCheckoutMutationTimeoutError extends Error{phase;code="PR_WORKFLOW_CHECKOUT_MUTATION_TIMEOUT";retryable=!1;constructor(phase){super(phase==="queue"?"BLOCKED: timed out waiting for the active PR workflow checkout mutation; the existing owner still holds serialization and must settle before retrying":"BLOCKED: PR workflow checkout mutation exceeded its execution deadline; serialization remains held until the in-flight action actually settles");this.phase=phase;this.name="PrWorkflowCheckoutMutationTimeoutError"}}});import{createHash as createHash49,randomUUID as randomUUID16}from"node:crypto";import*as fsp6 from"node:fs/promises";import*as path100 from"node:path";function bindPrReviewReentryBindingReader(reader){bindingReader=reader}async function currentBinding(directory,sessionID){if(!bindingReader)throw Error("BLOCKED: re-entry authorization binding reader is not bound (the PR workflow gate must bind it at module init)");return bindingReader(directory,sessionID)}function reentryAuthorizationFilePath(directory,sessionID){let relative26=path100.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`);return validateSwarmPath(directory,relative26)}function reentryAuthorizationImportedPath(directory,sessionID){return`${reentryAuthorizationFilePath(directory,sessionID)}.imported`}function reentryAuthorizationProjectionMarkerPath(directory,sessionID){return`${reentryAuthorizationFilePath(directory,sessionID)}.sqlite-projection`}function reentryAuthorizationCoordinationNamespace(sessionID){return`${AUTHORIZATION_COORDINATION_PREFIX}:${prWorkflowSessionFileStem(sessionID)}`}async function readAuthorizationFile(filePath){let raw;try{let stat12=await fsp6.stat(filePath);if(!stat12.isFile()||stat12.size>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store is not a bounded regular file");raw=await fsp6.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let decoded=JSON.parse(raw),parsed=AuthorizationFileSchema.safeParse(decoded);if(!parsed.success)throw Error(`reentry authorization store is invalid: ${parsed.error.issues.map((issue2)=>`${issue2.path.join(".")}: ${issue2.message}`).join("; ")}`);return parsed.data}function parseAuthorizationPayload(payload,sessionID){let decoded=JSON.parse(payload),parsed=AuthorizationFileSchema.safeParse(decoded);if(!parsed.success||parsed.data.sessionId!==sessionID)throw Error(`reentry authorization store is invalid for session "${sessionID}"`);return parsed.data}function readAuthorizationsFromCoordination(directory,sessionID){let row=getCoordinationState(directory,reentryAuthorizationCoordinationNamespace(sessionID),AUTHORIZATION_ENTITY_KEY);if(!row)return null;return{rowRevision:row.revision,rowGeneration:row.generation,store:parseAuthorizationPayload(row.payload,sessionID)}}async function renameWithRetryAsync(tempPath,targetPath){let lastError;for(let attempt=0;attempt<=_internals91.renameRetryDelaysMs.length;attempt++)try{await _internals91.renameImpl(tempPath,targetPath);return}catch(err){lastError=err;let code=err?.code;if(!code||!RETRYABLE_RENAME_CODES4.has(code))throw err;if(attempt<_internals91.renameRetryDelaysMs.length)await new Promise((resolve51)=>setTimeout(resolve51,_internals91.renameRetryDelaysMs[attempt]))}throw lastError}async function writeAuthorizationFile(filePath,file2){let serialized2=serializeAuthorizationFile(file2);if(Buffer.byteLength(serialized2,"utf8")>REENTRY_AUTHORIZATIONS_MAX_BYTES)throw Error("reentry authorization store exceeds its write bound");await fsp6.mkdir(path100.dirname(filePath),{recursive:!0});let tempPath=path100.join(path100.dirname(filePath),`.${path100.basename(filePath)}.${randomUUID16()}.tmp`);try{await fsp6.writeFile(tempPath,serialized2,{encoding:"utf8",flag:"wx"}),await renameWithRetryAsync(tempPath,filePath)}finally{await fsp6.rm(tempPath,{force:!0}).catch(()=>{return})}}async function fileExists2(filePath){try{return await fsp6.stat(filePath),!0}catch(error49){if(error49.code==="ENOENT")return!1;throw error49}}function serializeAuthorizationFile(file2){return`${JSON.stringify(file2,null,2)}
1279
1279
  `}async function readTextFileIfExists2(filePath){try{return await fsp6.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}}async function writeProjectionMarker2(filePath){await fsp6.mkdir(path100.dirname(filePath),{recursive:!0}),await fsp6.writeFile(filePath,`sqlite-projection
1280
1280
  `,"utf8")}async function collisionSafeImportedPath2(filePath){let canonical=`${filePath}.imported`;if(!await fileExists2(canonical))return canonical;for(let suffix=1;suffix<=1e4;suffix+=1){let candidate=`${canonical}.${suffix}`;if(!await fileExists2(candidate))return candidate}throw Error(`No collision-safe archive path available for ${path100.basename(filePath)}`)}async function archiveShadowSource2(filePath){if(!await fileExists2(filePath))return;await renameWithRetryAsync(filePath,await collisionSafeImportedPath2(filePath))}async function syncAuthorizationShadowProjection(directory,sessionID,store,options){let filePath=reentryAuthorizationFilePath(directory,sessionID);if(options.archiveLegacy&&await fileExists2(filePath))await archiveShadowSource2(filePath);await writeAuthorizationFile(filePath,store),await writeProjectionMarker2(reentryAuthorizationProjectionMarkerPath(directory,sessionID))}async function repairImportedAuthorizationShadow(directory,sessionID,store){let filePath=reentryAuthorizationFilePath(directory,sessionID),markerPath=reentryAuthorizationProjectionMarkerPath(directory,sessionID),live=await readTextFileIfExists2(filePath);if(live===null){await syncAuthorizationShadowProjection(directory,sessionID,store,{archiveLegacy:!1});return}let canonicalImportedExists=await fileExists2(reentryAuthorizationImportedPath(directory,sessionID)),markerExists=await fileExists2(markerPath),projected=serializeAuthorizationFile(store);if(canonicalImportedExists&&markerExists&&live===projected)return;if(canonicalImportedExists&&live===projected){await writeProjectionMarker2(markerPath);return}await syncAuthorizationShadowProjection(directory,sessionID,store,{archiveLegacy:!0})}async function readAuthorizationsAuthoritative(directory,sessionID){let existing=readAuthorizationsFromCoordination(directory,sessionID);if(existing)return await repairImportedAuthorizationShadow(directory,sessionID,existing.store),existing;let filePath=reentryAuthorizationFilePath(directory,sessionID),raw;try{raw=await fsp6.readFile(filePath,"utf8")}catch(error49){if(error49.code==="ENOENT")return null;throw error49}let legacy=await readAuthorizationFile(filePath);if(!legacy)return null;let outcome=importCoordinationOnce(directory,{source:path100.join("pr-review","reentry-authorizations",`${prWorkflowSessionFileStem(sessionID)}.json`),sourceDigest:createHash49("sha256").update(raw).digest("hex"),rowCount:legacy.authorizations.length,emptyNamespace:reentryAuthorizationCoordinationNamespace(sessionID)},()=>{let result=transitionCoordinationState(directory,{namespace:reentryAuthorizationCoordinationNamespace(sessionID),entityKey:AUTHORIZATION_ENTITY_KEY,expectedRevision:null,generation:1,status:"authorizations",payload:JSON.stringify(legacy)});if(result.outcome!=="applied")throw Error(`reentry authorization import failed: ${result.outcome}`)}),imported=readAuthorizationsFromCoordination(directory,sessionID);if(imported&&outcome==="imported")await syncAuthorizationShadowProjection(directory,sessionID,imported.store,{archiveLegacy:!0});return imported}function persistAuthorizationsAuthoritative(directory,sessionID,store,expectedRevision,generation){let result=transitionCoordinationState(directory,{namespace:reentryAuthorizationCoordinationNamespace(sessionID),entityKey:AUTHORIZATION_ENTITY_KEY,expectedRevision,generation,status:"authorizations",payload:JSON.stringify(store)});if(result.outcome!=="applied"&&result.outcome!=="revision_conflict"&&result.outcome!=="stale_generation")throw Error(`reentry authorization persistence failed: ${result.outcome}`);return{outcome:result.outcome}}function pruneAuthorizations(records,nowMs3){let unexpired=records.filter((record2)=>Date.parse(record2.expiresAt)>nowMs3),newest=(left,right)=>{let leftAt=left.consumedAt??left.createdAt,rightAt=right.consumedAt??right.createdAt;return leftAt===rightAt?0:leftAt>rightAt?-1:1},live=unexpired.filter((record2)=>!record2.consumedAt).sort(newest),consumed=unexpired.filter((record2)=>Boolean(record2.consumedAt)).sort(newest);return[...live,...consumed.slice(0,Math.max(0,MAX_PERSISTED_AUTHORIZATIONS-live.length))]}async function issuePrReviewReentryAuthorization(directory,sessionID,request){let trimmedSession=sessionID.trim();if(!trimmedSession)throw Error("BLOCKED: re-entry authorization requires an active sessionID");return withSessionStateMutation(directory,trimmedSession,async()=>{let binding=await currentBinding(directory,trimmedSession);if(!binding||binding.prHeadSha!==request.prHeadSha.toLowerCase())throw Error(`BLOCKED: re-entry authorization requires an active PR_REVIEW workflow bound to the declared head (active: ${binding?.prHeadSha??"(none)"})`);if(request.runId&&binding.runId&&request.runId!==binding.runId)throw Error("BLOCKED: re-entry authorization run does not match the active PR-review run");for(let attempt=0;attempt<MAX_AUTHORIZATION_WRITE_ATTEMPTS;attempt++){let existing=await readAuthorizationsAuthoritative(directory,trimmedSession),nowMs3=Date.now(),now=new Date(nowMs3).toISOString(),records=pruneAuthorizations(existing?.store.authorizations??[],nowMs3);if(records.filter((record3)=>!record3.consumedAt&&record3.role===request.role&&record3.generation===binding.generation).length>0)throw Error(`BLOCKED: an unconsumed re-entry authorization for role "${request.role}" at generation ${binding.generation} already exists; use it (one immediate Task dispatch) before issuing another`);if(records.filter((record3)=>!record3.consumedAt).length>=MAX_ACTIVE_AUTHORIZATIONS)throw Error(`BLOCKED: re-entry authorization store is at its bound of ${MAX_ACTIVE_AUTHORIZATIONS} active authorizations`);let record2={schemaVersion:1,authorizationId:randomUUID16(),sessionId:trimmedSession,...binding.workflowInstanceId?{workflowInstanceId:binding.workflowInstanceId}:{},...binding.runId?{runId:binding.runId}:{},prHeadSha:binding.prHeadSha,revisionDigest:binding.revisionDigest,role:request.role,generation:binding.generation,createdAt:now,expiresAt:new Date(nowMs3+AUTHORIZATION_TTL_MS).toISOString()},nextStore={schemaVersion:1,sessionId:trimmedSession,authorizations:[record2,...records].slice(0,MAX_PERSISTED_AUTHORIZATIONS)};if(persistAuthorizationsAuthoritative(directory,trimmedSession,nextStore,existing?.rowRevision??null,(existing?.rowGeneration??0)+1).outcome!=="applied")continue;return await syncAuthorizationShadowProjection(directory,trimmedSession,nextStore,{archiveLegacy:!1}),record2}throw Error("BLOCKED: re-entry authorization store changed concurrently; reload the active session state before retrying")})}function authorizationMatchesBinding(record2,binding){return binding.prHeadSha===record2.prHeadSha&&binding.revisionDigest===record2.revisionDigest&&binding.generation===record2.generation&&binding.workflowInstanceId===record2.workflowInstanceId&&binding.runId===record2.runId}async function hasPrReviewReentryAuthorizationAgainstBinding(directory,sessionID,request,binding){let trimmedSession=sessionID.trim();if(!trimmedSession)return!1;try{let existing=await readAuthorizationsAuthoritative(directory,trimmedSession);if(!existing)return!1;return pruneAuthorizations(existing.store.authorizations,Date.now()).some((record2)=>!record2.consumedAt&&record2.role===request.role&&record2.sessionId===trimmedSession&&authorizationMatchesBinding(record2,binding))}catch{return!1}}async function reservePrReviewReentryAuthorizationAgainstBinding(directory,sessionID,request,binding){let trimmedSession=sessionID.trim();if(!trimmedSession)return null;try{for(let attempt=0;attempt<MAX_AUTHORIZATION_WRITE_ATTEMPTS;attempt++){let existing=await readAuthorizationsAuthoritative(directory,trimmedSession);if(!existing)return null;let nowMs3=Date.now(),records=pruneAuthorizations(existing.store.authorizations,nowMs3),sameCallIndex=records.findIndex((record2)=>record2.consumedCallId===request.callID&&record2.role===request.role&&record2.sessionId===trimmedSession&&Date.parse(record2.expiresAt)>nowMs3),index=sameCallIndex>=0?sameCallIndex:records.findIndex((record2)=>!record2.consumedAt&&record2.role===request.role&&record2.sessionId===trimmedSession&&Date.parse(record2.expiresAt)>nowMs3);if(index<0){if(records.length!==existing.store.authorizations.length){let prunedStore={...existing.store,authorizations:records};if(persistAuthorizationsAuthoritative(directory,trimmedSession,prunedStore,existing.rowRevision,existing.rowGeneration+1).outcome!=="applied")continue;await syncAuthorizationShadowProjection(directory,trimmedSession,prunedStore,{archiveLegacy:!1})}return null}let candidate=records[index];if(!authorizationMatchesBinding(candidate,binding))return null;if(candidate.consumedCallId===request.callID)return candidate;let consumed={...candidate,consumedAt:new Date(nowMs3).toISOString(),consumedCallId:request.callID};records[index]=consumed;let nextStore={...existing.store,authorizations:records};if(persistAuthorizationsAuthoritative(directory,trimmedSession,nextStore,existing.rowRevision,existing.rowGeneration+1).outcome!=="applied")continue;return await syncAuthorizationShadowProjection(directory,trimmedSession,nextStore,{archiveLegacy:!1}),consumed}return null}catch{return null}}var AUTHORIZATION_TTL_MS=600000,MAX_ACTIVE_AUTHORIZATIONS=8,MAX_PERSISTED_AUTHORIZATIONS=32,REENTRY_AUTHORIZATIONS_MAX_BYTES=65536,AUTHORIZATION_COORDINATION_PREFIX="pr-review.reentry-authorizations",AUTHORIZATION_ENTITY_KEY="authorizations",MAX_AUTHORIZATION_WRITE_ATTEMPTS=5,bindingReader,PrReviewReentryAuthorizationRecordSchema,AuthorizationFileSchema,RENAME_RETRY_DELAYS_MS4,RETRYABLE_RENAME_CODES4,_internals91;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"]);_internals91={AUTHORIZATION_TTL_MS,MAX_ACTIVE_AUTHORIZATIONS,reentryAuthorizationFilePath,reentryAuthorizationCoordinationNamespace,pruneAuthorizations,authorizationMatchesBinding,hasPrReviewReentryAuthorizationAgainstBinding,renameImpl:(from,to)=>fsp6.rename(from,to),renameRetryDelaysMs:RENAME_RETRY_DELAYS_MS4,renameWithRetryAsync,writeAuthorizationFile}});function zeroOutputResult(result){let outputRef=result.outputRef?.trim(),text=result.text?.trim()??"";return!outputRef&&text.length===0&&(result.chars??0)===0}function classifyPrReviewCircuitSignal(record2){if(!CIRCUIT_TERMINAL_DELEGATION_STATUSES.has(record2.status))return null;let result=record2.terminalResult?.result??record2.result,providerClass=result?.terminalErrorClass?.category;if(result?.terminalErrorClass&&providerClass){if(record2.status!=="error")return{kind:"ignored",reason:"cancellation"};if(result.terminalErrorClass.kind==="provider")return{kind:"provider_terminal",providerClass,batchId:record2.batchId??"",laneId:record2.laneId??"",terminalAtMs:record2.terminalResult?.recordedAt??record2.completedAt??record2.updatedAt??record2.createdAt??0};if(result.terminalErrorClass.kind==="aborted")return{kind:"ignored",reason:"cancellation"};if(result.terminalErrorClass.kind==="output_length")return{kind:"ignored",reason:"validation"};return{kind:"ignored",reason:"unknown"}}if(result?.workflowLaneFailureClass==="liveness")return{kind:"ignored",reason:"host_abandonment"};switch(record2.status){case"error":return{kind:"ignored",reason:"unknown"};case"stale":return{kind:"ignored",reason:"stale_observation"};case"cancelled":return{kind:"ignored",reason:"cancellation"};case"completed":return zeroOutputResult(result??{})?{kind:"ignored",reason:"parser"}:null;default:return null}}function scanPrReviewCircuitEvidence(signals,generation,waterlineMs){let byKey=new Map;for(let signal of signals){if(signal.kind!=="provider_terminal")continue;if(signal.terminalAtMs<=0||waterlineMs!==void 0&&signal.terminalAtMs<=waterlineMs)continue;let key2=`${generation}\x00${signal.batchId}\x00${signal.laneId}`,existing=byKey.get(key2);if(!existing||existing.signal.terminalAtMs<signal.terminalAtMs)byKey.set(key2,{signal})}let grouped=new Map,ordered=[...byKey.values()].sort((left,right)=>right.signal.terminalAtMs-left.signal.terminalAtMs||left.signal.providerClass.localeCompare(right.signal.providerClass)||left.signal.batchId.localeCompare(right.signal.batchId)||left.signal.laneId.localeCompare(right.signal.laneId));for(let{signal}of ordered){let list=grouped.get(signal.providerClass)??[];if(list.length<PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT)list.push(signal);grouped.set(signal.providerClass,list)}return grouped}function adoptPrReviewCircuit(raw,nowMs3){if(raw===void 0||raw===null)return{kind:"absent"};let asV2=PrReviewCircuitRecordV2Schema.safeParse(raw);if(asV2.success)return{kind:"v2",record:asV2.data};let asLegacy=PrReviewCircuitLegacyRecordSchema.safeParse(raw);if(asLegacy.success)return{kind:"migrated",record:freshRecord(nowMs3,!0),diagnostic:{code:"migrated_legacy_circuit",legacySignatureCount:asLegacy.data.contributors.length}};let body=JSON.stringify(raw),hash3="";try{let h=2166136261;for(let index=0;index<body.length;index+=1)h^=body.charCodeAt(index),h=Math.imul(h,16777619);hash3=(h>>>0).toString(16).padStart(8,"0")}catch{hash3="unserializable"}return{kind:"malformed",diagnostic:{code:"malformed_circuit_dropped",bodyHash8:hash3,byteLength:body.length}}}function freshRecord(nowMs3,withWaterline){return{version:2,state:"CLOSED",generation:1,contributors:[],...withWaterline?{evidenceWaterline:new Date(nowMs3).toISOString()}:{}}}function advancePrReviewCircuit(current,input){let record2=current??freshRecord(input.nowMs,!1);if(record2.state==="CLOSED"){let evidence2=scanPrReviewCircuitEvidence(input.laneSignals,record2.generation,record2.evidenceWaterline?Date.parse(record2.evidenceWaterline):void 0),best=null;for(let[providerClass,lanes]of evidence2){if(lanes.length<input.threshold)continue;if(!best||lanes.length>best.lanes.length||lanes.length===best.lanes.length&&providerClass.localeCompare(best.providerClass)<0)best={providerClass,lanes}}if(!best)return{action:"admit",changed:!1};let openedAt=new Date(input.nowMs).toISOString();return{action:"block",reason:"circuit_open",changed:!0,record:{...record2,state:"OPEN",providerClass:best.providerClass,contributors:best.lanes.map((signal2)=>({batchId:signal2.batchId,laneId:signal2.laneId,terminalAt:new Date(signal2.terminalAtMs).toISOString()})),openedAt,openUntil:new Date(input.nowMs+input.openDurationMs).toISOString()}}}if(record2.state==="OPEN"){let openUntilMs=record2.openUntil?Date.parse(record2.openUntil):0;if(input.nowMs<openUntilMs)return{action:"block",reason:"circuit_open",changed:!1};if(!input.admission)return{action:"block",reason:"circuit_open",changed:!1};return{action:"admit_as_probe",changed:!0,record:{...record2,state:"HALF_OPEN",probe:{batchId:input.admission.batchId,laneId:input.admission.laneId,admittedAt:new Date(input.nowMs).toISOString()}}}}let probe2=record2.probe;if(!probe2)return{action:"block",reason:"probe_in_flight",changed:!1};if(input.admission&&input.admission.batchId===probe2.batchId&&!input.probeObservation)return{action:"admit_as_probe",changed:!1};if(!input.probeObservation)return{action:"block",reason:"probe_in_flight",changed:!1};let{terminalStatus,signal}=input.probeObservation;if(signal?.kind==="provider_terminal"){let contributor={batchId:probe2.batchId,laneId:probe2.laneId,terminalAt:new Date(signal.terminalAtMs).toISOString()},contributors=[...record2.contributors.filter((entry)=>!(entry.batchId===contributor.batchId&&entry.laneId===contributor.laneId)),contributor].slice(-PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT);return{action:"block",reason:"circuit_open",changed:!0,record:{...record2,state:"OPEN",contributors,openUntil:new Date(input.nowMs+input.openDurationMs).toISOString(),probe:void 0}}}if(terminalStatus==="completed"&&signal===null)return{action:"admit",changed:!0,record:{version:2,state:"CLOSED",generation:record2.generation+1,contributors:[],evidenceWaterline:new Date(input.probeObservation.terminalAtMs||input.nowMs).toISOString()}};return{action:"block",reason:"circuit_open",changed:!0,record:{...record2,state:"OPEN",openUntil:new Date(input.nowMs+input.openDurationMs).toISOString(),probe:void 0}}}function resolvePrReviewResiliencePolicy(policy){let defaults=DEFAULT_PR_REVIEW_RESILIENCE_CONFIG;return{enabled:policy?.enabled??defaults.enabled,canaryProbeMs:policy?.canary_probe_ms??defaults.canary_probe_ms,statusProbeTimeoutMs:policy?.status_probe_timeout_ms??defaults.status_probe_timeout_ms,correlatedFailureThreshold:policy?.correlated_failure_threshold??defaults.correlated_failure_threshold,maxRetryAttemptsAfterInitial:policy?.max_retry_attempts_after_initial??defaults.max_retry_attempts_after_initial,circuitOpenDurationMs:policy?.circuit_open_duration_ms??defaults.circuit_open_duration_ms}}function resetPrReviewResilienceForReEnable(args2){let previousGeneration=args2.previousCircuit&&"version"in args2.previousCircuit?args2.previousCircuit.generation:1;return{...freshRecord(args2.nowMs,!0),generation:previousGeneration+1}}function rollbackPrReviewCircuitProbe(circuit,nowMs3,openDurationMs){if(circuit.state!=="HALF_OPEN"||!circuit.probe)return circuit;return{...circuit,state:"OPEN",openUntil:new Date(nowMs3+openDurationMs).toISOString(),probe:void 0}}var PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT=768,PrReviewCircuitLegacyRecordSchema,PrReviewCircuitRecordV2Schema,PrReviewCircuitRecordSchema,CIRCUIT_TERMINAL_DELEGATION_STATUSES;var init_circuit=__esm(()=>{init_zod();init_schema();PrReviewCircuitLegacyRecordSchema=exports_external.object({signature:exports_external.string().min(1).max(512),count:exports_external.number().int().min(2).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1)}).strict()).min(2).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),openedAt:exports_external.string().min(1)}).strict(),PrReviewCircuitRecordV2Schema=exports_external.object({version:exports_external.literal(2),state:exports_external.enum(["CLOSED","OPEN","HALF_OPEN"]),generation:exports_external.number().int().min(1),providerClass:exports_external.string().min(1).max(128).optional(),contributors:exports_external.array(exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),terminalAt:exports_external.string().min(1)}).strict()).max(PR_REVIEW_CIRCUIT_CONTRIBUTOR_LIMIT),openedAt:exports_external.string().min(1).optional(),openUntil:exports_external.string().min(1).optional(),evidenceWaterline:exports_external.string().min(1).optional(),probe:exports_external.object({batchId:exports_external.string().min(1),laneId:exports_external.string().min(1),admittedAt:exports_external.string().min(1)}).strict().optional()}).strict(),PrReviewCircuitRecordSchema=exports_external.union([PrReviewCircuitLegacyRecordSchema,PrReviewCircuitRecordV2Schema]),CIRCUIT_TERMINAL_DELEGATION_STATUSES=new Set(["completed","error","cancelled","stale"])});import{createHash as createHash50}from"node:crypto";import*as fs64 from"node:fs/promises";import*as path101 from"node:path";function parseCandidateConfidence(value){if(typeof value!=="string")throw Error("Invalid candidate confidence: expected LOW, MEDIUM, or HIGH");let normalized=value.trim().toUpperCase();if(normalized!=="LOW"&&normalized!=="MEDIUM"&&normalized!=="HIGH")throw Error(`Invalid candidate confidence "${value}": expected LOW, MEDIUM, or HIGH`);return{label:normalized,score:CONFIDENCE_SCORE[normalized]}}function tokens(value){return new Set(value.toLocaleLowerCase("en-US").replace(/[^a-z0-9]+/g," ").split(/\s+/).filter((token)=>token.length>=3&&!TOKEN_STOPWORDS.has(token)).map((token)=>TOKEN_ALIASES[token]??token))}function semanticSimilaritySets(a,b){if(a.size===0||b.size===0)return 0;let intersection2=0;for(let token of a)if(b.has(token))intersection2+=1;return intersection2/(a.size+b.size-intersection2)}function normalizedLocation(location){let file2=location.file.replaceAll("\\","/").trim().toLocaleLowerCase("en-US"),line=Number(location.line),lineEnd=location.lineEnd===void 0?line:Number(location.lineEnd);return`${file2}:${line}-${lineEnd}`}function normalizedCategory(category){return category.trim().toLocaleLowerCase("en-US")}function severity(value){if(value==="CRITICAL"||value==="HIGH"||value==="MEDIUM"||value==="LOW"||value==="INFO"||value==="NONE")return value;throw Error(`Invalid finding severity "${String(value)}"`)}function action(value){if(value==="route_to_reviewer"||value==="route_to_critic"||value==="report"||value==="suppress_with_reason"||value==="handoff_to_feedback")return value;return"report"}function status(value){if(value==="UNRESOLVED"||value==="CONFIRMED"||value==="DISPROVED"||value==="NON_ACTIONABLE"||value==="PRE_EXISTING")return value;return"UNRESOLVED"}function provenanceKey(value){return value.identity.trim()}function uniqueProvenance(values){let unique2=new Map;for(let value of values){if(typeof value.identity!=="string"||!value.identity.trim())throw Error("Finding provenance identity must be non-empty");let key2=provenanceKey(value);if(!unique2.has(key2))unique2.set(key2,{...value})}return[...unique2.values()].sort((a,b)=>provenanceKey(a).localeCompare(provenanceKey(b)))}function sameFinding(left,leftTokens,right,rightTokens){if(normalizedCategory(left.category)!==normalizedCategory(right.category))return!1;if(normalizedLocation(left.location)!==normalizedLocation(right.location))return!1;if(left.finding.trim()===right.finding.trim())return!0;return semanticSimilaritySets(leftTokens,rightTokens)>=0.3}function findingId(value){let material=`${normalizedLocation(value.location)}|${normalizedCategory(value.category)}|${[...tokens(value.finding)].sort().join(",")}`,hash3=2166136261;for(let char of material)hash3^=char.charCodeAt(0),hash3=Math.imul(hash3,16777619);return`finding-${(hash3>>>0).toString(16).padStart(8,"0")}`}function lowestConfidence(values){return values.reduce((lowest,value)=>CONFIDENCE_RANK[value]<CONFIDENCE_RANK[lowest]?value:lowest)}function synthesizePrReviewFindings(input){if(input.candidates.length>MAX_FINDING_SYNTHESIS_CANDIDATES)throw Error(`Finding synthesis accepts at most ${MAX_FINDING_SYNTHESIS_CANDIDATES} candidates`);let groups=[],groupTokens=[],diagnostics=[];for(let raw of input.candidates){if(!raw||typeof raw!=="object")throw Error("Finding candidate must be an object");let candidate={...raw,finding:typeof raw.finding==="string"?raw.finding.trim():"",severity:severity(raw.severity),confidence:parseCandidateConfidence(raw.confidence).label,category:typeof raw.category==="string"?raw.category.trim():""};if(!candidate.finding||!candidate.category||!candidate.location?.file)throw Error("Finding candidate requires non-empty finding, category, and location");let candidateTokens=tokens(candidate.finding),existingIndex=-1;for(let index=0;index<groups.length;index++)if(sameFinding(groups[index][0],groupTokens[index],candidate,candidateTokens)){existingIndex=index;break}if(existingIndex>=0)groups[existingIndex].push(candidate);else groups.push([candidate]),groupTokens.push(candidateTokens)}let findings=groups.map((group)=>{let first=group[0],provenance=uniqueProvenance(group.flatMap((candidate)=>Array.isArray(candidate.provenance)?candidate.provenance:[candidate.provenance])),severities=group.map((candidate)=>severity(candidate.severity)),confidenceValues=group.map((candidate)=>parseCandidateConfidence(candidate.confidence).label),finalSeverity=severities.reduce((highest,value)=>SEVERITY_RANK[value]>SEVERITY_RANK[highest]?value:highest),confidence=provenance.length>=2?"HIGH":lowestConfidence(confidenceValues);if(new Set(severities).size>1||new Set(confidenceValues).size>1)diagnostics.push(`conservative disagreement at ${normalizedLocation(first.location)}`);let finalAction=group.map((candidate)=>action(candidate.action)).reduce((mostRestrictive,value)=>ACTION_RANK[value]>ACTION_RANK[mostRestrictive]?value:mostRestrictive),finalStatus=group.map((candidate)=>status(candidate.status)).reduce((mostConservative,value)=>STATUS_RANK[value]>STATUS_RANK[mostConservative]?value:mostConservative),sourceFindingIds=[...new Set(group.flatMap((candidate)=>typeof candidate.sourceFindingId==="string"?[candidate.sourceFindingId]:[]))].sort();return{id:findingId(first),finding:first.finding,severity:finalSeverity,action:finalAction,confidence,confidenceScore:CONFIDENCE_SCORE[confidence],agreementCount:provenance.length,category:first.category,location:{...first.location},provenance,status:finalStatus,sourceFindingIds}});return{policyVersion:FINDING_POLICY_VERSION,findings,diagnostics}}function evaluateFinalFindingPolicy(input){if(input.policyVersion!==FINDING_POLICY_VERSION)throw Error(`Unsupported finding policy version ${input.policyVersion}`);let invalidProvenance=input.coverage.provenance==="invalid",noCoverage=input.coverage.quality==="none"||input.coverage.kind==="base"&&input.coverage.quality==="partial"&&input.findings.length===0,coverageDisposition=invalidProvenance?"INVALID_PROVENANCE":noCoverage?"NO_COVERAGE":input.coverage.quality==="degraded"&&input.coverage.disclosed?"DEGRADED_DISCLOSED":input.coverage.quality==="complete"?"COMPLETE":"PARTIAL";if(input.finalStatus!=="COMPLETE"||invalidProvenance||noCoverage)return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["INCOMPLETE"],coverageDisposition,blockingFindingIds:[]};let blockingFindingIds=[];for(let[index,value]of input.findings.entries()){let currentSeverity=severity(value.severity),currentStatus=String(value.status).toUpperCase(),currentAction=action(value.action);if(!(currentStatus==="UNRESOLVED"||currentStatus==="UNVERIFIED"||currentStatus==="CONFIRMED")||currentSeverity==="NONE")continue;if(currentSeverity==="CRITICAL"||currentSeverity==="HIGH"||currentSeverity==="MEDIUM"&&currentAction!=="report")blockingFindingIds.push(String(value.id??index))}if(blockingFindingIds.length>0)return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds};if(coverageDisposition==="DEGRADED_DISCLOSED"||coverageDisposition==="PARTIAL")return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds};return{policyVersion:FINDING_POLICY_VERSION,permittedVerdicts:["APPROVE","REQUEST_CHANGES","INCOMPLETE"],coverageDisposition,blockingFindingIds}}function settleCriticFinding(input){if(input.outcome==="NEEDS_MORE_EVIDENCE")return{terminal:!1,status:input.outcome,finalFinding:{...input.finding},handoffFindingIds:[]};if(input.outcome==="DISPROVED")return{terminal:!0,status:input.outcome,finalFinding:{...input.finding,status:"DISPROVED",severity:"NONE",action:"suppress_with_reason"},handoffFindingIds:[]};if(input.outcome==="DOWNGRADED"&&input.finalSeverity===void 0)throw Error("DOWNGRADED critic finding requires an explicit final severity");let finalSeverity=severity(input.finalSeverity??input.finding.severity);if(input.outcome==="UPHELD"&&finalSeverity==="NONE")throw Error("UPHELD critic finding cannot have NONE severity");if(input.outcome==="DOWNGRADED"&&finalSeverity==="CRITICAL")throw Error("DOWNGRADED critic finding cannot remain CRITICAL");let finalAction=action(input.finalAction??input.finding.action);return{terminal:!0,status:input.outcome,finalFinding:{...input.finding,severity:finalSeverity,action:finalAction},handoffFindingIds:finalAction==="handoff_to_feedback"&&input.finding.status!=="DISPROVED"?[input.finding.id]:[]}}function deriveFeedbackHandoffFindingIds(records){return[...new Set(records.filter((record2)=>record2.status==="CONFIRMED"&&record2.next_action==="handoff_to_feedback").map((record2)=>record2.finding_id))].sort()}function assessTerminalReadiness(input){let blockers=[];if(!input.baseReceipt?.valid)blockers.push("BASE_RECEIPT_MISSING");if(input.reviewerReceipts.length===0||input.reviewerReceipts.some((receipt)=>!receipt.valid))blockers.push("REVIEWER_RECEIPT_MISSING");if(!input.criticReceipt?.valid)blockers.push("CRITIC_RECEIPT_MISSING");if(input.criticReceipt?.valid&&input.criticSettlements&&input.criticSettlements.length===0)blockers.push("CRITIC_SETTLEMENT_MISSING");if(input.council.enabled&&!input.council.receipt?.valid)blockers.push("COUNCIL_RECEIPT_MISSING");if(input.coverage.kind==="micro"&&input.coverage.provenance==="invalid")blockers.push("MICRO_PROVENANCE_INVALID");if(input.coverage.quality==="degraded"&&!input.coverage.disclosed)blockers.push("MICRO_DEGRADATION_UNDISCLOSED");if(input.criticSettlements?.some((settlement)=>!settlement.terminal))blockers.push("CRITIC_SETTLEMENT_INCOMPLETE");return{ready:blockers.length===0,blockers,degradedCoverageDisclosed:input.coverage.quality==="degraded"&&input.coverage.provenance==="valid"&&input.coverage.disclosed===!0}}function reviewOutcomeSynthesisDigest(synthesis){return createHash50("sha256").update(JSON.stringify(synthesis),"utf8").digest("hex")}function safeTaskId(taskId){let value=taskId.trim();if(!/^[A-Za-z0-9_.-]{1,128}$/.test(value))throw Error("Review outcome taskId must be a bounded path-safe identifier");return value}async function persistReviewOutcome(input){let sessionId=input.routeReceipt.sessionId.trim(),taskId=safeTaskId(input.routeReceipt.taskId);if(!sessionId)throw Error("Review outcome sessionId must be non-empty");let relativeEvidence=path101.join("pr-review",taskId,"finding-policy.json"),evidencePath=validateSwarmPath(input.projectRoot,relativeEvidence),eventsPath=coreEventsFilePath(input.projectRoot),evidence2={schemaVersion:FINDING_POLICY_VERSION,sessionId,taskId,routeReceipt:input.routeReceipt,synthesis:input.synthesis,synthesisDigest:reviewOutcomeSynthesisDigest(input.synthesis),persistedAt:new Date().toISOString()};await ensurePrWorkflowSafeParentDirectory(input.projectRoot,evidencePath);let alreadyPersisted=!1;try{let existing=JSON.parse(await fs64.readFile(evidencePath,"utf8"));if(!(existing.schemaVersion===FINDING_POLICY_VERSION&&existing.sessionId===sessionId&&existing.taskId===taskId&&JSON.stringify(existing.routeReceipt)===JSON.stringify(input.routeReceipt)&&JSON.stringify(existing.synthesis)===JSON.stringify(input.synthesis)&&existing.synthesisDigest===reviewOutcomeSynthesisDigest(input.synthesis)))throw Error("Review outcome already exists with conflicting route or synthesis data");alreadyPersisted=!0}catch(error49){if(error49.code!=="ENOENT")throw error49}if(!alreadyPersisted)await writeAtomicJson2(input.projectRoot,evidencePath,evidence2);let reviewEvents=readReviewEvents(input.projectRoot,sessionId,taskId),{events}=reviewEvents,auditWindowComplete=reviewEvents.coverage!=="truncated"&&!reviewEvents.truncated,shouldEnsureAuditEvents=!alreadyPersisted||auditWindowComplete;if(shouldEnsureAuditEvents&&!events.some((event)=>event.type==="review.route.receipt"))appendCoreEventSync(input.projectRoot,{type:"review.route.receipt",sessionId,taskId,receiptVersion:input.routeReceipt.version});if(shouldEnsureAuditEvents&&!events.some((event)=>event.type==="review.finding.synthesis"))appendCoreEventSync(input.projectRoot,{type:"review.finding.synthesis",sessionId,taskId,policyVersion:FINDING_POLICY_VERSION,findingCount:Array.isArray(input.synthesis.findings)?input.synthesis.findings.length:0});return{persisted:!0,evidencePath,eventsPath}}async function readReviewOutcome(input){let taskId=safeTaskId(input.taskId),evidencePath=validateSwarmPath(input.projectRoot,path101.join("pr-review",taskId,"finding-policy.json")),evidence2=JSON.parse(await fs64.readFile(evidencePath,"utf8"));if(evidence2.sessionId!==input.sessionId||evidence2.taskId!==taskId||evidence2.schemaVersion!==FINDING_POLICY_VERSION)throw Error("Review outcome evidence identity or schema mismatch");if(!evidence2.synthesis||evidence2.synthesisDigest!==reviewOutcomeSynthesisDigest(evidence2.synthesis))throw Error("Review outcome evidence synthesis integrity mismatch");let reviewEvents=readReviewEvents(input.projectRoot,input.sessionId,taskId),{events}=reviewEvents;if(reviewEvents.coverage!=="truncated"&&!reviewEvents.truncated&&(!events.some((event)=>event.type==="review.route.receipt")||!events.some((event)=>event.type==="review.finding.synthesis")))throw Error("Review outcome evidence audit events are incomplete");return{evidence:evidence2,events,auditCoverage:reviewEvents.coverage}}function readReviewEvents(projectRoot,sessionId,taskId){let read=readCoreEvents(projectRoot);return{events:read.text.split(`